1.netty构建http服务涉及API
- 编解码器
HttpRequestDecoder 解码器
HttpResponseEncoder 编码器
HttpServerCodec 解码器和编码器
HttpObjectAggregator
该解码器针对请求体req.content() 也是ChannelInboundHandlerAdapter类型
2.基于netty开发类似springboot+web的简单版框架
1.netty核心代码如下:
- netty-server, 封装netty的启动器
package cn.qu.netty.web;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
public class NettyServer {
final static Log log = Log.createLog();
public static NettyServer createNettyServer() {
NettyServer nettyServer = new NettyServer();
return nettyServer;
}
/**
* @param port
* @param queueSize netty 线程组中的队列最大容量
* @throws InterruptedException
*/
public void start(int port, int queueSize, String[] scannerPackage) throws Exception {
NioEventLoopGroup bossGroup = null;
NioEventLoopGroup workerGroup = null;
ApplicationContext applicationContext = new ApplicationContext(scannerPackage);
HandlerMappingProvider handlerMappingProvider = new HandlerMappingProvider(applicationContext);
FilterProvider filterProvider = new FilterProvider(applicationContext);
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
ChannelFuture channelFuture = bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, queueSize).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(64 * 1024)) // 最大5mb
// .addLast(new CheckIpInboundHandler()) 抽象到过滤器
.addLast(new DefaultHandler(filterProvider, handlerMappingProvider));
}
}).bind(port).sync();
log.log("netty server start success : port=" + port);
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
- DefaultHandler
代码实现的不好,就不粘了,以后优化
2.流程图:
3.web api设计思路如下:
- 1.大致抽象出以下模型
WebApplication 启动器
NettyServer 服务器
ApplicationContext 应用上下文持有所有bean实例
HandlerMapping 基于springmvc的接口映射 pojo
HandlerMappingProvider
OncePerRequestFilter 路由前置过滤器
OnceAfterRequestFilter 路由后置过滤器
FilterProvider
ParameterResolver 参数解析器
Log 日志组件
配置文件解析组件(未实现)
- 2. 完整项目地址