如何制作一个Netty的springboot-starter
最近出于学习的目的,想整个springboot-starter玩玩,然后又正好在玩netty,所以就决定搞一个netty-springboot-starter,目的主要是学习,初步设想有以下功能:
- 可以通过配置一键启动服务端或者客户端
- 通过注解就可以实现自己的数据处理Handler
- 内置协议,可以通过配置进行切换如:http、webSocket、自定义协议等
- 内置心跳机制、重连机制
目前以上功能基本实现,接下来看看功能使用介绍
一、使用
我们以服务端来举例,可打包到本地仓库引入使用
服务端
需要配置启动参数,协议那里如果不自定义则必填否则服务端不会启动(怎么自定义后面说),下面我们介绍内置的三种协议的配置启动
内嵌协议
HTTP
http-config为http参数配置项,不配也可以有默认值
配置如下:
数据处理类自己编写,如同netty一样,只需要打上 @NettyServerHandler 注解即可,如:
@NettyServerHandler
public class HttpBaseHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private final static Logger log= LoggerFactory.getLogger(HttpBaseHandler.class);
@Resource
private ApplicationEventPublisher applicationContext;
public HttpBaseHandler(ApplicationEventPublisher applicationContext){
this.applicationContext=applicationContext;
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest t) throws Exception {
log.info("http请求 uri:{},method:{}",t.uri(),t.method());
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.content().writeBytes(JSON.toJSONBytes("Hello"));
response.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON+";charset=UTF-8");
response.headers().add(HttpHeaderNames.CONTENT_LENGTH,response.content().readableBytes());
channelHandlerContext.writeAndFlush(response);
}
}
启动springboot项目测试:
打开浏览器,访问127.0.0.1:8888,就可以看到请求结果了
WebSocket
由于WebSocket也同样会采用Http编解码,所以http的配置也同时会满足WebSocket,一样都有默认值,可以不配置
配置如下:
数据处理类自己编写,如同netty一样,只需要打上 @NettyServerHandler 注解即可,如:
@NettyServerHand