【问题标题】:How can I access a Netty Handler method from outside of the normal flow如何从正常流程之外访问 Netty 处理程序方法
【发布时间】:2012-12-30 09:38:27
【问题描述】:

我正在尝试将 Netty(版本 3.6.1.final)集成到我们当前的系统中,以便替换当前的 NIO 代码。

目前我们有一个消息传递总线,其中事件排队等待其他侦听器处理,并将另一个事件放回总线上以供进一步处理。

在我的 Netty 业务逻辑处理程序的 messageReceived() 方法中,我将向总线添加一个输入请求。我要传递的一件事是来自 Netty 事件消息的数据。

我认为我应该在这个 InputEvent 中传递 ChannelHandlerContext 以及接收到的数据/消息。这样最终在处理 OutputEvent 时,它可以使用最初传递的 ChannelHandlerContext 将处理后的数据发送回正确的 Netty Channel 上的请求客户端。

那么处理 OutputEvent 的 Output 任务如何与 Netty 绑定呢?

我是否使用 ChannelHandlerContext 作为处理数据的输入来发出一些调用。我不想捆绑输出任务。

来自 Netty 处理程序的代码 sn-p。

public void messageReceived(
        ChannelHandlerContext ctx, MessageEvent e) {

    byte[] message = (byte[])e.getMessage();

    try {
            data.add(message);
        }
    catch( IOException ioe )
        {
            logger.error(ioe);
        }

    InputEvent ie = new InputEvent( ctx, this, data.getBuffer() );

    try {
              bus.enqueue(ie);
    }
    catch( Exception ex )
   {
      logger.error(ex);
   }

来自输出处理器的代码 sn-p。

public void run() {


    // note that the OutputEvent (event) is available here.  This is not a Netty event.
    ChannelHandlerContext ctx = event.getHandlerContext();
    ClientChannel handler = event.getHandler();

    // I need to send the data in event.getBuffer() back.

// Now what do I do here???


…
…
…

}

谢谢。

【问题讨论】:

    标签: netty


    【解决方案1】:
        // Make a new connection.
        ChannelFuture connectFuture =
            bootstrap.connect(new InetSocketAddress(host, port));
    
        // Wait until the connection is made successfully.
        Channel channel = connectFuture.awaitUninterruptibly().getChannel();
    
        // Get the handler instance to retrieve the answer.
        FactorialClientHandler handler =
            (FactorialClientHandler) channel.getPipeline().getLast();//get("your handler name")
    

    【讨论】:

      【解决方案2】:

      您只需调用:

      InputEvent event = ...
      ChannelHandlerContext ctx = ....
      ctx.write(event.getBuffer());
      

      或者:

      InputEvent event = ...
      Channel channel = ....
      channel.write(event.getBuffer());
      

      【讨论】:

      • 就这么简单。伟大的! Netty 将极大地帮助我们解决 NIO 问题。谢谢诺曼。
      • 我想问这个。当我将数据写入 ctx 或通道时,这基本上会将其交给通道并且我不必在输出任务中等待写入周期完成吗?通过写周期,我的意思是让数据到达客户端。谢谢。
      • 是的,它不会等待...如果您需要等待,您可以在返回的 ChannelFuture 上调用 await*(),但不要在 IO 线程中执行此操作..
      • 感谢您的确认。我不想等。我只想把信放在邮箱里,然后继续我的路。 :) 再次感谢诺曼。
      • 我认为最好将 event.getBuffer() 返回的 ByteBuffer 转换为 ChannelBuffer。所以我使用了: ChannelBuffer cb = ChannelBuffers.wrappedBuffer(event.getBuffer());然后做了:ctx.getChannel().write(cb);
      猜你喜欢
      • 2020-01-31
      • 1970-01-01
      • 2013-09-22
      • 2016-11-25
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多