NettyGateWayContainer.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package cn.nosum.gateway.container;
  2. import cn.nosum.common.annotation.Adaptive;
  3. import cn.nosum.common.util.Convert;
  4. import cn.nosum.common.util.PropertiesUtil;
  5. import cn.nosum.gateway.handler.build.HandlerProvider;
  6. import io.netty.bootstrap.ServerBootstrap;
  7. import io.netty.channel.*;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. @Adaptive
  13. public class NettyGateWayContainer implements GateWayContainer {
  14. Logger logger= LoggerFactory.getLogger(NettyGateWayContainer.class);
  15. private int port = Convert.toInt(PropertiesUtil.getProperty("container.port"));
  16. public void start(){
  17. // Boss线程
  18. EventLoopGroup bossGroup = new NioEventLoopGroup();
  19. // Worker线程
  20. EventLoopGroup workerGroup = new NioEventLoopGroup();
  21. try {
  22. ServerBootstrap server = new ServerBootstrap();
  23. server.group(bossGroup, workerGroup)
  24. .channel(NioServerSocketChannel.class)
  25. // 子线程处理类 , Handler
  26. .childHandler(HandlerProvider.newHandlerChannel())
  27. // 针对主线程的配置 分配线程最大数量 128
  28. .option(ChannelOption.SO_BACKLOG, 128)
  29. // 针对子线程的配置 保持长连接
  30. .childOption(ChannelOption.SO_KEEPALIVE, true);
  31. // 启动服务器
  32. ChannelFuture f = server.bind(port).sync();
  33. logger.debug("NettyGateWayContainer启动成功,访问端口号是:{}",port);
  34. f.channel().closeFuture().sync();
  35. }catch (Exception e){
  36. e.printStackTrace();
  37. }finally {
  38. // 关闭线程池
  39. bossGroup.shutdownGracefully();
  40. workerGroup.shutdownGracefully();
  41. }
  42. }
  43. }