java - 将 Netty 与业务逻辑结合使用

标签 java netty

我使用 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 还是不同的东西?例如,在我的特定情况下,我有以下类(class):

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 中执行操作的常见方法。你能澄清一下吗?

最佳答案

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

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

关于java - 将 Netty 与业务逻辑结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356205/

相关文章:

java如何调用外部unix命令

java - 使用 Reactor 抛出异常的正确方法

java - 如何按特定数据段对数组进行排序?

netty - 使用 vertx web 客户端版本 4.0.0 时出现 java.lang.IllegalAccessError

java - 在方法中本地分配对象成员变量有好处吗?

java - 在netty客户端中运行synchronize方法

netty - netty中bytebuf的复用

java - 如何跟踪可能重叠的应用程序不同组件的不同性能改进?

java - 从一个 jsp 页面到另一个页面执行 href 时创建一个新 session , session 变量返回为 null

java - 轻量级低延迟的 Java 网络库?