【问题标题】:Using netty with business logic使用带有业务逻辑的 netty
【发布时间】:2017-11-19 01:40:17
【问题描述】:

我对使用 netty 的经验并不多,对ChannelPipeline 的文档有疑问。这就是它的确切含义:

 static final EventExecutorGroup group = new DefaultEventExecutorGroup(16);
 ...

 ChannelPipeline pipeline = ch.pipeline();

 pipeline.addLast("decoder", new MyProtocolDecoder());
 pipeline.addLast("encoder", new MyProtocolEncoder());

 // Tell the pipeline to run MyBusinessLogicHandler's event handler methods
 // in a different thread than an I/O thread so that the I/O thread is not blocked by
 // a time-consuming task.
 // If your business logic is fully asynchronous or finished very quickly, you don't
 // need to specify a group.
 pipeline.addLast(group, "handler", new MyBusinessLogicHandler());

我不太了解MyBusinessLogicHandler 类。它应该实现DuplexChannelHandler 还是不同的东西?例如,在我的特殊情况下,我有以下课程:

public class Packet{}

我想将一些字节序列解码为Packet,给MyBusinessLogicHandler,它会产生一些Packet。然后再次将其编码为字节流以发送回客户端。我目前是这样看的:

public class MyBusinessLogicHandler extends SimpleChannelInboundHandler<MyModel>{
    public void channelRead0(ChannelHandlerContext ctx, Packet msg){
         Packet rslt = null;
         //Do some complicated business logic
         ctx.write(rslt);
    }
}

我不确定这是否是在 netty 中做事的常用方法。你能澄清一下吗?

【问题讨论】:

    标签: java netty


    【解决方案1】:

    是的。这是实现MyBusinessLogicHandler 的完全正确的方法。你不需要DuplexChannelHandler,因为在你的管道中你已经有MyProtocolEncoder(我想实现ChannelOutboundHandler)。 因此,当您调用 ctx.write(rslt) 时,您会触发出站处理程序的写入事件。

    DuplexChannelHandler 仅在您想在同一个类中实现编码器和解码器的情况下才有用。例如,您可以通过加入MyProtocolEncoderMyProtocolDecoder 来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      相关资源
      最近更新 更多