java - 在 Netty 4 中迁移 sendUpstream

标签 java netty

我正在从 netty 3 迁移到 netty 4。我有一个管道处理程序,充当经典过滤器,拦截/处理途中不合规的消息,并将合规消息铲到上游。

根据文档 ( http://netty.io/wiki/new-and-noteworthy.html ),我预计使用 ctx.fireInboundBufferUpdated()代替ctx.sendUpStream()中继入站。但是,我发现这不起作用,但是 ChannelHandlerUtil.addToNextInboundBuffer()做。我希望获得一些指导:

  1. 我对当前文档的断言 ctx.sendUpstream -> ctx.fireInboundBufferUpdated 感到困惑并且,
  2. 这种情况下的最佳实践是什么(如果与我在下面所做的不同)。

代码:

//The pipeline

public class ServerInitializer extends ChannelInitializer<SocketChannel> {

 @Override
 public void initChannel(SocketChannel ch) throws Exception {
     ChannelPipeline p = ch.pipeline();
     p.addLast("decoder", new HttpRequestDecoder());
     p.addLast("encoder", new HttpResponseEncoder());
     p.addLast("inbound", InboundHttpRequestFilter.INSTANCE);
     p.addLast("handler", handlerClass.newInstance());

 }
}

//The filter
public class InboundHttpRequestFilter extends
        ChannelInboundMessageHandlerAdapter<Object> {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        ... discard/handle as necessary …;
        //ctx.fireInboundBufferUpdated(); - doesn't propagate upstream
        ChannelHandlerUtil.addToNextInboundBuffer(ctx, msg); // sends upstream
    }
}

最佳答案

试试这个:

ctx.nextInboundMessageBuffer().add(msg)

Javadoc:

Interface ChannelHandlerContext
MessageBuf<Object>  nextInboundMessageBuffer()
    Return the MessageBuf of the next ChannelInboundMessageHandler in the pipeline.

Netty 4 多个处理程序示例:

MultiHandlerServer.java

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

public class MultiHandlerServer {
    private static final Logger logger = LoggerFactory.getLogger(MultiHandlerServer.class);

    final int port;

    public MultiHandlerServer(final int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            final ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LineBasedFrameDecoder(8192),
                                    new StringDecoder(Charset.forName("UTF-8")),
                                    new MultiHandler01(), new MultiHandler02());
                        }
                    });

            final ChannelFuture future = serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final MultiHandlerServer client = new MultiHandlerServer(8080);
        client.run();
    }
}

MultiHandler01.java

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 */
class MultiHandler01 extends ChannelInboundMessageHandlerAdapter<String> {
    private Logger logger = LoggerFactory.getLogger(MultiHandler01.class);

    MultiHandler01() {
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        logger.info(String.format("Handler01 receive message: %s", msg));
        ctx.nextInboundMessageBuffer().add(msg);
        ctx.fireInboundBufferUpdated();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Exception caught: %s", ctx.channel().remoteAddress(), cause);
        ctx.close();
    }
}

MultiHandler02.java

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 */
class MultiHandler02 extends ChannelInboundMessageHandlerAdapter<String> {
    private Logger logger = LoggerFactory.getLogger(MultiHandler02.class);

    MultiHandler02() {
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        logger.info(String.format("Handler02 receive message: %s", msg));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Exception caught: %s", ctx.channel().remoteAddress(), cause);
        ctx.close();
    }
}

关于java - 在 Netty 4 中迁移 sendUpstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469072/

相关文章:

java - 在 JBoss 7 AS 中使用 Netty

java - HTTP组件、ReSTLet、Apache Mina和Netty的区别

java - for 循环在第一次迭代中停止

java - GWT - 如何在 @Entity 注释的类之外实现 RequestContext 方法?

java - 当我们使用自己的线程池时,netty可以线程安全吗?如果netty可以,为什么?

netty - 是否可以在同一个应用程序中使用 Netty 3.x 和 4.0,或者会不会有类名冲突?

java - 使用 netty 3.4.2.Final 通过代理工作

java - 如何使用 Stripes Framework 在 Web 浏览器中显示 JFreeChart

java - 第一个 JSP 页面 — 使用 2D 数组 — 页面未填充

java - int 的基本算术运算 - Java