1.执行Channel
的任何一个操作,都会验证是否是对应的EventLoop
中所包含的那个线程在执行。如果不是,则以提交任务的的形式让其执行所有所有属于Channel
的同一个操作。任务的提交顺序与任务的执行顺序是完全一致的。
2.在Netty中,Channel
的实现是线程安全的,基于此,我们可以存储一个Channel
的引用,并且在需要向远程端点发送数据时,通过这个引用来调用Channel
相应的方法;即便当时有很多线程使用它,也不会出现多线程问题。而且,消息一定会按照顺序发送出去。
3.不要将长时间执行的耗时任务放入到EventLoop
的执行队列中,因为他会将一直阻塞该线程所对应的所有Channel
上的其他任务。
如果我们需要进行阻塞调用或是耗时的操作,我们需要使用一个专门的EventExecutor
作为业务线程池。一种方式是在ChannelHandler
的回调方法中,使用自己的业务线程池,例如:
public class MyServerHandler extends SimpleChannelInboundHandler<String>{
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress()+","+msg);
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(()->{
//业务逻辑
});
}
或者借助于Netty提供的向ChannelPipeline
添加ChannelHanlder
调用的addLast
方法来传递EventExecutorGroup
:
public class MyInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
EventExecutorGroup eventExecutors = new new DefaultEventExecutorGroup(1);
//添加Executor
pipeline.addLast(eventExecutors,new MyServerHandler());
}
}