代码之家  ›  专栏  ›  技术社区  ›  James

触发按需TCP消息到可重新连接、不可共享的Netty管道的正确方法是什么?

  •  1
  • James  · 技术社区  · 7 年前

    我有一个netty 4.x tcp客户端应用程序,它有一个重新连接的监听器,我想不出一种方法来实现一个触发器(http、mq等),它将写入套接字通道。

    到目前为止,我试图添加 write(ByteBuf msg) 对我 ChannelInboundHandler ,通过以下方式 another example ,但是对于我的重新连接侦听器,在重新连接时出现以下异常:

    ... is not a @Sharable handler, so can't be added or removed multiple times.
    

    我是netty的新手,所以我不确定用户事件触发器是否能解决这个问题。

    重新连接代码:

    if (!future.isSuccess()) {
        future.channel().eventLoop().schedule(() -> {
            bootstrap.connect().addListener(this);
        }, reconnectDelayTimeNanos, TimeUnit.NANOSECONDS);
    } else {
        future.channel().closeFuture().addListener((ChannelFuture cf) -> {
            bootstrap.connect().addListener(this);
        });
    }
    

    引导代码:

    final MyHandler myHandler = new MyHandler();
    final EventLoopGroup requestGroup = new NioEventLoopGroup();
    final Bootstrap requestBootstrap = new Bootstrap()
            .group(requestGroup)
            .channel(NioSocketChannel.class)
            .remoteAddress("localhost", 9999)
            .option(ChannelOption.SO_KEEPALIVE, true);
    requestBootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel ch) {
            ch.pipeline().addLast(myHandler);
        }
    });
    

    为了能够使用 写入(bytebuf msg) 方法,处理程序需要在 ChannelInitializer .

    我希望能够从触发器(http、mq等)向管道、不可共享处理程序等发送消息。

    目前,我得到了以下例外情况:

    …不是@sharable处理程序,因此不能多次添加或删除。
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Norman Maurer    7 年前

    你需要标记你的 MyHandler 通过注释 @Sharable 或重写 isSharable() 方法。这说明在这种情况下,您需要确保处理程序是线程安全的。

    推荐文章