Netty服务器开发模式
public class MyServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new MyServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
-
创建两个事件循环组
EventLoopGroup
,即bossGroup
和workerGroup
。 -
bossGroup
接收事件后,转发给workerGroup
。
NioEventLoopGroup
- 构造函数如下:bossGroup的线程数通常指定为1
public NioEventLoopGroup() {
this(0);
}
//指定线程个数
public NioEventLoopGroup(int nThreads) {
this(nThreads, (Executor) null);
}
-
NioEventLoopGroup
实现了EventLoopGroup
接口,EventLoopGroup
文档说明:// 提供将Channel可以注册到EventLoopGroup中的若干方法 public interface EventLoopGroup extends EventExecutorGroup { //返回下一个即将被使用的EventLoop @Override EventLoop next(); //将Channel注册到EventLoop中,注册完成后,返回的ChannelFuture对象会得到通知 ChannelFuture register(Channel channel); //传入的ChannelPromise对象在注册完成后也会得到通知 ChannelFuture register(ChannelPromise promise); }
ChannelPromise
接口继承了ChannelFuture
接口。
- 构造函数中的其他参数的默认值:
-
selectorProvider
: SelectorProvider.provider() -
selectStrategyFactory
:DefaultSelectStrategyFactory.INSTANCE -
rejectedExecutionHandler
:RejectedExecutionHandlers.reject()
-
NioEventLoopGroup
的父类MultithreadEventLoopGroup: 当传入的
nThreads
线程数为0时,会使用默认线程数字段DEFAULT_EVENT_LOOP_THREADS
,它的计算逻辑如下:public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup { private static final int DEFAULT_EVENT_LOOP_THREADS; static { DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt( "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2)); } protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) { super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args); } }
网友评论