NettyGatewayContainer.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package cn.nosum.container;
  2. import cn.nosum.handler.GateWayHandler;
  3. import cn.nosum.handler.HttpRequestHandler;
  4. import io.netty.bootstrap.ServerBootstrap;
  5. import io.netty.channel.*;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;
  9. import io.netty.handler.codec.http.HttpRequestDecoder;
  10. import io.netty.handler.codec.http.HttpResponseEncoder;
  11. //Netty就是一个同时支持多协议的网络通信框架
  12. public class NettyGatewayContainer {
  13. private int port = 8888;
  14. public void start(){
  15. // Boss线程
  16. EventLoopGroup bossGroup = new NioEventLoopGroup();
  17. // Worker线程
  18. EventLoopGroup workerGroup = new NioEventLoopGroup();
  19. try {
  20. ServerBootstrap server = new ServerBootstrap();
  21. server.group(bossGroup, workerGroup)
  22. .channel(NioServerSocketChannel.class)
  23. // 子线程处理类 , Handler
  24. .childHandler(new ChannelInitializer<SocketChannel>() {
  25. // 客户端初始化处理
  26. protected void initChannel(SocketChannel client) throws Exception {
  27. // Netty对HTTP协议的封装,顺序有要求
  28. // HttpResponseEncoder 编码器
  29. client.pipeline().addLast(new HttpResponseEncoder());
  30. // HttpRequestDecoder 解码器
  31. client.pipeline().addLast(new HttpRequestDecoder());
  32. // 业务逻辑处理
  33. client.pipeline().addLast(new HttpRequestHandler());
  34. client.pipeline().addLast(new GateWayHandler());
  35. }
  36. })
  37. // 针对主线程的配置 分配线程最大数量 128
  38. .option(ChannelOption.SO_BACKLOG, 128)
  39. // 针对子线程的配置 保持长连接
  40. .childOption(ChannelOption.SO_KEEPALIVE, true);
  41. // 启动服务器
  42. ChannelFuture f = server.bind(port).sync();
  43. System.out.println("已启动,监听的端口是:" + port);
  44. f.channel().closeFuture().sync();
  45. }catch (Exception e){
  46. e.printStackTrace();
  47. }finally {
  48. // 关闭线程池
  49. bossGroup.shutdownGracefully();
  50. workerGroup.shutdownGracefully();
  51. }
  52. }
  53. }