netty从客户端收到后如何转发收到的消息

时间:2018-06-26 08:35:32

标签: netty

服务器A收到请求后,将生成一个http包并查询另一个服务器B。服务器B响应200状态码后,服务器A在其随后的入站通道处理程序中进行另一个查询。因为我不想阻塞IO线程等待服务器B的响应,所以BBDuplexHandler仅在触发channelRead之后才添加到服务器管道中。服务器A中的服务器和客户端都是使用netty实现的。我的问题是如何将Origin_request传递给BBDuplexHandler?还是在客户端通道读取后如何将origin_request传递到服务器A管道?

my idea

代码以netty代理为例:

服务器:

public class ServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1500) );
        p.addLast(new ServerChannelHandler());
}

public class ServerChannelHandler extends ChannelDuplexHandler {
    SomeClient client;

    @Override
    public void channeInactive(ChannelHandlerContext ctx) {
        if (client != null) {
            client.closeOnFlush();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        client = new SomeClient(ctx);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        client.send(msg);
    }   
}

客户端:

   public static class SomeClientChannelInitializer extends ChannelInitializer<Channel> {
        private ChannelHandlerContext inboundCtx;

        public SomeClientChannelInitializer(ChannelHandlerContext ctx) {
            this.inboundCtx = ctx;
        }

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(1500));
            pipeline.addLast(new ClientChannel(inboundCtx));
        }
    }

    public static class ClientChannel extends SimpleChannelInboundHandler {
        Channel inboundChannel;
        ChannelHandlerContext inboundCtx;

        public ClientChannel(ChannelHandlerContext inboundCtx) {
            this.inboundCtx = inboundCtx;
            this.inboundChannel = inboundCtx.channel();
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) {
            ServerDuplexHandler.closeOnFlush(inboundChannel);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            // msg to a pojo.
            inboundChannel.pipeline().addAfter(inboundCtx.name(), null, new BBDuplexHandler(pojo));
            inboundCtx.fireChannelRead(originRequest);  // how to forward this originRequest??
        }
    }

0 个答案:

没有答案