public class NettyServer implements ServletContextListener { private static Logger log = Logger.getLogger(NettyServer.class); /*線程數量不宜設置過高,線程切換非常耗時*/ public static final EventExecutorGroup exec = new DefaultEventExecutorGroup( Runtime.getRuntime().availableProcessors()*2, (ThreadFactory) r -> { Thread thread = new Thread(r); thread.setName("custom-tcp-exec-"+r.hashCode()); return thread; }, 100000, RejectedExecutionHandlers.reject() ); //boss線程監聽端口,worker線程負責數據讀寫 public static final EventLoopGroup boss = Epoll.isAvailable()? new EpollEventLoopGroup(1) : new NioEventLoopGroup(1); public static final EventLoopGroup worker = Epoll.isAvailable()? new EpollEventLoopGroup() : new NioEventLoopGroup(); /** * 功能描述:omcat服務器啟動時,netty啟動 * @return void * @Author: guoliangbo * @Date: 2019/9/24 13:18 */ public static void nettyStart(ApplicationContext applicationContext){ // 初始化websocket WebSocket.setApplicationContext(applicationContext); // getRedisVal(); try{ // 初始化ServerBootstrap實例, 此實例是netty服務端應用開發的入口 ServerBootstrap bootstrap = new ServerBootstrap(); // 把兩個線程組加入進來 初始化的主從"線程池" bootstrap.group(boss,worker); // 指定使用NioServerSocketChannel這種類型通道 由於是服務端,故而是NioServerSocketChannel bootstrap.channel(Epoll.isAvailable()? EpollServerSocketChannel.class : NioServerSocketChannel.class); // 一定要使用去綁定具體的事件處理器 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); //pipeline.addLast(new NettyServerInHandler(applicationContext)); pipeline.addLast(exec, "handler", new NettyServerInHandler(applicationContext)); } }); // 最大的等待連接數 默認128 bootstrap.option(ChannelOption.SO_BACKLOG,10000); // 配置子通道也就是SocketChannel的選項 // 我們已經有了應用層的心跳檢測機制,也不需要開啟此參數 bootstrap.childOption(ChannelOption.SO_KEEPALIVE,false); bootstrap.childOption(ChannelOption.TCP_NODELAY,false); //bootstrap.childOption(ChannelOption.SO_RCVBUF,1024 * 4); //bootstrap.childOption(ChannelOption.SO_SNDBUF,1024 * 4); // 綁定並偵聽某個端口 ChannelFuture future = bootstrap.bind(Integer.valueOf(StartOnLoad.NETTY_PORT)).sync(); Logger.getLogger(NettyServer.class).debug("server start ......"); MetricsUtils.start(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); }finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } }