1. 程式人生 > 實用技巧 >netty ServerBootstrap 簡單分析

netty ServerBootstrap 簡單分析

netty 作為java生態中提供非阻塞非同步io,基於事件驅動的高效能網路框架,得到了廣泛的應用。

我們在編寫服務端的程式碼時使用netty 提供給我們的ServerBootstrap 引導啟動類,

通常的程式碼如下:

EventLoopGroup boss = new NioEventLoopGroup(1); 
 EventLoopGroup works= new NioEventLoopGroup(); 
      try{
             ServerBootstrap bootstrap = new ServerBootstrap();
             bootstrap.group(boss, works)
                .channel(NioServerSocketChannel.
class) //使用非同步模式,netty 會使用反射建立NioServerSocketChannel // 設定tcp 半連線佇列的大小, //The {@code backlog} argument is the requested maximum number of // pending connections on the socket. // 最大引數受net.core.somaxconn 引數限制(linux) .option(ChannelOption.SO_BACKLOG, 1024) .childOption(ChannelOption.SO_KEEPALIVE,
true) // 啟動negal演算法,容量小的包延遲傳送,等到更多容量小的包一起傳送,有利於提高傳輸效率 但是會增加使用者延時 .childOption(ChannelOption.TCP_NODELAY, true) .childHandler(null); ChannelFuture f = bootstrap.bind(port).sync(); //使用同步方式繫結(阻塞但是繫結很快就能完成) f.channel().closeFuture().sync(); //
同步 會一直阻塞main執行緒 }finally{ workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } NioEventLoop 啟動的執行緒是非守護執行緒 (main 執行緒結束,NioEventLoop 中的執行緒會繼續執行 jvm 不會退出) f.channel().closeFuture()// 去掉將同步阻塞

// main 執行緒退出,NioEventLoop中的執行緒保持執行

使用netty時 我們寫channelhandle 時絕對不能阻塞當前執行緒,耗時的操作可以放入執行緒池中執行,應該保證當前執行緒能夠儘快響應。