🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 绑定端口并启动 ``` public void start() { try { // 绑定端口,同步等待成功 ChannelFuture future = server.bind(new InetSocketAddress(8888)).sync(); // 等待服务监听端口关闭 future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 优雅退出,释放线程池资源 mainGroup.shutdownGracefully(); subGroup.shutdownGracefully(); } } ``` ### 遇到过的问题 使用`new InetSocketAddress(8888)`无法启动: 原因:多网卡; ``` public void start() { this.future = server.bind("192.168.30.51",8888); if (future.isSuccess()) { log.info("启动 Netty 成功"); } } ``` ## Netty线程组启动时,默认线程为多少? ``` public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup { private static final InternalLogger logger = InternalLoggerFactory.getInstance(MultithreadEventLoopGroup.class); private static final int DEFAULT_EVENT_LOOP_THREADS; static { DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt( "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2)); if (logger.isDebugEnabled()) { logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS); } } ... } ``` 默认取-Dio.netty.eventLoopThreads,如果该系统参数也没有指定,则为可用的CPU内核数 × 2。 ## 其他资料 1. [netty源码浅析--线程启动](https://blog.csdn.net/c275046758/article/details/52262167)