我使用 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
仅当您想在同一个类中实现编码器和解码器时才有用。例如,您可以通过加入 MyProtocolEncoder
和 MyProtocolDecoder
来实现这一点。
关于java - 将 Netty 与业务逻辑结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356205/