netty 构建Reactor主从多线程模型
netty版本
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>
启动类
public static void main(String[] args) throws InterruptedException {
// 主线程 不从事工作,分派工作
NioEventLoopGroup parent = new NioEventLoopGroup();
// 从线程 从事工作
NioEventLoopGroup child = new NioEventLoopGroup();
try {
// 启动
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(parent, child) // 设置主从
.channel(NioServerSocketChannel.class)// 设置nio双向通道
.childHandler(new HelloServerInit());// 自处理器
// 绑定端口 同步等待启动
ChannelFuture channelFuture = serverBootstrap.bind(8011).sync();
// 监听时间,同步
channelFuture.channel().closeFuture().sync();
} finally {
// 关闭
parent.shutdownGracefully();
child.shutdownGracefully();
}
}
自定义处理器
public class HelloServerInit extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// 通过chanel 获取通道
ChannelPipeline pipeline = socketChannel.pipeline();
// 设置编解码助手类
pipeline.addLast("HttpServerCodec",new HttpServerCodec());
// 设置自定义的助手类
pipeline.addLast("ConsumeHandler",new ConsumeHandler());
}
}
自定义助手类
public class ConsumeHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext context, HttpObject obj) throws Exception {
Channel channel = context.channel();
if (obj instanceof HttpRequest) {
// 获取客户端ip
System.out.println(channel.remoteAddress());
// 设置数据以及编码
ByteBuf content = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);
// 设置数据并设置请求头信息
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
// 写入并刷新
context.writeAndFlush(response);
}
}
}
访问方式
1、浏览器直接访问 localhost:端口
2、linux curl ip:端口