2022-05-31_netty服务端ServerBootstrap业务handler绑定对应的线程学习笔记

20220531_netty服务端ServerBootstrap业务handler绑定对应的线程学习笔记

1概述

我们知道netty服务端端口绑定监听的时候,会创建一个NioServerSocketChannel,同时register选择boss中一个线程进行连接监听处理。

config().group().register(channel)

本节主要分析一下,pipeline().addLast()中增加业务hander时,如何与特定的线程进行绑定的,主要分2中情况:

  1. 增加到默认的事件循环组中(ch.pipeline().addLast(new TestChannelHandler1())
  2. 增加到自定义的事件循环组中(ch.pipeline().addLast(eventExecutorGroup3, new TestChannelHandler2()))
.handler(new ChannelInitializer<ServerSocketChannel>() { // for boss
                    @Override
                    public void initChannel(ServerSocketChannel ch) {
                        // 服务端channel的流水线,增加业务 handler
                        // 1.默认和 channel 在同一个线程
                        ch.pipeline().addLast(new TestChannelHandler1());

1.1DefaultChannelHandlerContext类图

DefaultChannelHandlerContext:handler作为通道流水线中每个节点的存储单元。

DefaultChannelHandlerContext:handler 业务处理器
AbstractChannelHandlerContext:name 名称,pipeline 挂载的管道,executor挂载的线程,executionMask(出入栈类型)
image-20220531161425664.png

1.1.1构建DefaultChannelHandlerContext

    private AbstractChannelHandlerContext newContext(EventExecutorGroup group, String name, ChannelHandler handler) {
        // 构建 DefaultChannelHandlerContext
        return new DefaultChannelHandlerContext(this, childExecutor(group), name, handler);
    }

1.1.2认线程池(group ==null),设置executor时序

private EventExecutor childExecutor(EventExecutorGroup group) {
        if (group == null) { // 直接返回
            return null;
        }
        Boolean pinEventExecutor = channel.config().getOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP);
        if (pinEventExecutor != null && !pinEventExecutor) {
            return group.next();
        }
        Map<EventExecutorGroup, EventExecutor> childExecutors = this.childExecutors;
        if (childExecutors == null) {
            // Use size of 4 as most people only use one extra EventExecutor.
            childExecutors = this.childExecutors = new IdentityHashMap<EventExecutorGroup, EventExecutor>(4);
        }
        // Pin one of the child executors once and remember it so that the same child executor
        // is used to fire events for the same channel.
        EventExecutor childExecutor = childExecutors.get(group);
        if (childExecutor == null) {
            childExecutor = group.next();
            childExecutors.put(group, childExecutor);
        }
        return childExecutor;
    }
// E:\workdirectory\Dev\study\netty-4.1\transport\src\main\java\io\netty\channel\DefaultChannelPipeline.java
@Override
    public final ChannelPipeline addLast(ChannelHandler... handlers) {
        return addLast(null, handlers);
    }
@Override
    public final ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler) {
        final AbstractChannelHandlerContext newCtx;
        synchronized (this) {
            checkMultiplicity(handler);

            newCtx = newContext(group, filterName(name, handler), handler); // 此时,executor 仍为null

            addLast0(newCtx);

            // If the registered is false it means that the channel was not registered on an eventLoop yet.
            // In this case we add the context to the pipeline and add a task that will call
            // ChannelHandler.handlerAdded(...) once the channel is registered.
            if (!registered) {
                newCtx.setAddPending();
                callHandlerCallbackLater(newCtx, true);
                return this;
            }

            EventExecutor executor = newCtx.executor(); // here,重要的地方来了,核心的判断,得到一个 eventExecutor
            if (!executor.inEventLoop()) { // 默认线程组,inEventLoop:true
                callHandlerAddedInEventLoop(newCtx, executor);
                return this;
            }
        }
        callHandlerAdded0(newCtx);
        return this;
    }

1.1.2.1核心的判断

// 核心的判断
@Override
    public EventExecutor executor() {
        if (executor == null) { // 如果当前没有挂接线程,则与 channnel共用同一个线程
            return channel().eventLoop();
        } else {
            return executor;
        }
    }

1.1.3自定义线程池(group != null),设置executor时序

    @Override
    public final ChannelPipeline addLast(EventExecutorGroup executor, ChannelHandler... handlers) {
        ObjectUtil.checkNotNull(handlers, "handlers");

        for (ChannelHandler h: handlers) {
            if (h == null) {
                break;
            }
            addLast(executor, null, h);
        }

        return this;
    }
private EventExecutor childExecutor(EventExecutorGroup group) {
        if (group == null) {
            return null;
        }
       // go on,自定义线程组 
        Boolean pinEventExecutor = channel.config().getOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP);
        if (pinEventExecutor != null && !pinEventExecutor) {
            return group.next();
        }
        Map<EventExecutorGroup, EventExecutor> childExecutors = this.childExecutors;
        if (childExecutors == null) {
            // Use size of 4 as most people only use one extra EventExecutor.
            childExecutors = this.childExecutors = new IdentityHashMap<EventExecutorGroup, EventExecutor>(4);
        }
        // Pin one of the child executors once and remember it so that the same child executor
        // is used to fire events for the same channel.
        EventExecutor childExecutor = childExecutors.get(group);
        if (childExecutor == null) { 
            childExecutor = group.next();  // here,轮询得到一个 eventExecutor
            childExecutors.put(group, childExecutor);
        }
        return childExecutor;
    }

1.1.3.1核心的判断

// E:\workdirectory\Dev\study\netty-4.1\common\src\main\java\io\netty\util\concurrent\MultithreadEventExecutorGroup.java
@Override
    public EventExecutor next() {
        return chooser.next();
    }
// E:\workdirectory\Dev\study\netty-4.1\common\src\main\java\io\netty\util\concurrent\DefaultEventExecutorChooserFactory.java
  @Override
        public EventExecutor next() {
            return executors[idx.getAndIncrement() & executors.length - 1];
        }

2代码示例

2.1testReregisterByKikop

@Test
    public void testReregisterByKikop() throws InterruptedException {

        // 线程池1,max:8
        // class: NioEventLoop
        // 并不是一下子线程全部创建
        // poolName:nioEventLoopGroup
        // Character.toLowerCase(poolName.charAt(0)) + poolName.substring(1)
        // prefix = poolName + '-' + poolId.incrementAndGet() + '-';
        // 线程名称定义:nioEventLoopGroup(类驼峰名)-1(工厂标识)-ID(自增)
        EventLoopGroup group1 = newEventLoopGroup();

        // 线程池3,max:2
        // // class: DefaultEventExecutor
        final EventExecutorGroup eventExecutorGroup3 = new DefaultEventExecutorGroup(2);

        ServerBootstrap bootstrap = new ServerBootstrap();
        ChannelFuture future = bootstrap.channel(newChannel()).group(group1)
                .childHandler(new ChannelInitializer<SocketChannel>() { // for work
                    @Override
                    public void initChannel(SocketChannel ch) {
                    }
                }).handler(new ChannelInitializer<ServerSocketChannel>() { // for boss
                    @Override
                    public void initChannel(ServerSocketChannel ch) {
                        // 服务端channel的流水线,增加业务 handler
                        // 1.默认和 channel 在同一个线程
                        ch.pipeline().addLast(new TestChannelHandler1());
                        ch.pipeline().addLast(new TestChannelHandler12());
                        ch.pipeline().addLast(new TestChannelHandler13());
                        ch.pipeline().addLast(new TestChannelHandler14());
                        // eventExecutorGroup 从这里面选一个 defaultEventExecutor,TestChannelHandler2对应线程池3
                        // ch.pipeline().addLast(eventExecutorGroup3, new TestChannelHandler2());
                        ch.pipeline().addLast(new TestChannelHandler2());


                    }
                })
                .bind(8888).awaitUninterruptibly();

        EventLoop eventExecutors = future.channel().eventLoop();
        showThreadProperties("eventExecutors", eventExecutors);


        // Wait until the connection is closed.
        future.channel().closeFuture().sync();

    }

2.2TestChannelHandler1

private void showThreadProperties(String executorName, EventExecutor executor) {
        if (executor instanceof SingleThreadEventExecutor) {
            ThreadProperties threadProperties = ((SingleThreadEventExecutor) executor).threadProperties();
            System.out.println(executorName + ":" + threadProperties.name() + ",id" + threadProperties.id());
        }
    }

private static final class TestChannelHandler1 extends ChannelDuplexHandler {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            super.channelActive(ctx);
            System.out.println(this.getClass().toString() + ":" + Thread.currentThread().getName()
                    + ",id:" + Thread.currentThread().getId());
        }
    }
class io.netty.channel.AbstractEventLoopTest$TestChannelHandler2:nioEventLoopGroup-2-1,id:12
class io.netty.channel.AbstractEventLoopTest$TestChannelHandler14:nioEventLoopGroup-2-1,id:12
class io.netty.channel.AbstractEventLoopTest$TestChannelHandler13:nioEventLoopGroup-2-1,id:12
class io.netty.channel.AbstractEventLoopTest$TestChannelHandler12:nioEventLoopGroup-2-1,id:12
class io.netty.channel.AbstractEventLoopTest$TestChannelHandler1:nioEventLoopGroup-2-1,id:12
eventExecutors:nioEventLoopGroup-2-1,id12

总结

参考

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容