Netty底层系统架构

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());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值