首页   快速返回

netty耗时任务处理     所属分类 netty
netty io线程中不能执行耗时操作
将耗时任务添加到业务线程池执行

handler中提交任务到线程池  灵活 按需提交任务
pipeline  添加 handler 时 指定线程池  , 整个 handler 都提交给业务线程池 ,不够灵活。
ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);
ChannelPipeline addLast(ChannelHandler... handlers);




EventExecutorGroup bizGroup = new DefaultEventExecutorGroup(32);

ChannelInitializer

protected void initChannel(SocketChannel ch)throws Exception {
ChannelPipeline p = ch.pipeline();
pipeline.addLast(bizGroup,new MyBizHandler());
...
}


  private void write(Object msg, boolean flush, ChannelPromise promise) {

        DefaultChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        // 判断当前线程是否是IO线程 , 是 直接执行 ,否则 提交任务到内部队列
        if (executor.inEventLoop()) {
            next.invokeWrite(msg, promise);
            if (flush) {
                next.invokeFlush();
            }
        } else {
            int size = channel.estimatorHandle().size(msg);
            if (size > 0) {
                ChannelOutboundBuffer buffer = channel.unsafe().outboundBuffer();
                // Check for null as it may be set to null if the channel is closed already
                if (buffer != null) {
                    buffer.incrementPendingOutboundBytes(size);
                }
            }
            Runnable task;
            if (flush) {
                task = WriteAndFlushTask.newInstance(next, msg, size, promise);
            }  else {
                task = WriteTask.newInstance(next, msg, size, promise);
            }
            safeExecute(executor, task, promise, msg);
        }
    }

上一篇     下一篇
dubbo性能相关参数

netty实战笔记

netty中的future和promise

netty4 ChannelInboundHandler 使用

ChannelPipeline和ChannelInitializer

netty ByteBuf 使用