将 netty 与业务逻辑结合使用
Using netty with business logic
我对 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
class。它应该实施 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
仅在您想在同一个 class 中同时实现编码器和解码器的情况下才有用。例如,您可以加入 MyProtocolEncoder
和 MyProtocolDecoder
.
我对 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
class。它应该实施 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
仅在您想在同一个 class 中同时实现编码器和解码器的情况下才有用。例如,您可以加入 MyProtocolEncoder
和 MyProtocolDecoder
.