将netty与业务逻辑结合使用

时间:2017-11-17 17:28:17

标签: java netty

我对使用netty并没有太多经验,对ChannelPipeline的文档有疑问。以下是它的确切内容:


var createClosure

我不太了解 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中执行操作的常用方法。你能澄清一下吗?

1 个答案:

答案 0 :(得分:2)

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

只有在您希望在同一个类中实现编码器和解码器的情况下,

DuplexChannelHandler才有用。例如,您可以加入MyProtocolEncoderMyProtocolDecoder