Netty入门四http

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 日志组件

配置文件解析组件(未实现)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值