Apache camel netty 自定义编码器和解码器示例

Apache camel netty custom encoder and decoder sample

Apache camel netty tcp 组件文档(http://camel.apache.org/netty.html)说,

编码器

A custom ChannelHandler class that can be used to perform special marshalling of outbound payloads. Must override org.jboss.netty.channel.ChannelDownStreamHandler.

解码器

A custom ChannelHandler class that can be used to perform special marshalling of inbound payloads. Must override org.jboss.netty.channel.ChannelUpStreamHandler.

你能给我一个关于 how/what 的例子来覆盖 class 吗?我想要自定义 tcp encoder/decoder 到 read/write 字节。

这个class和它的超级class是编码器,你可以用它作为例子:org.jboss.netty.handler.codec.string.StringEncoder

"Using multiple codecs" 标题中的 netty 页面上的示例中还使用了其他 classes,您可以查看源代码以了解它们如何使用界面。

如果不行,最好看看 netty 项目,看看编码器的单元测试。

在 netty 文档中有使用编码器和解码器的 ChannelHandler 的代码。来自文档:

ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4);

StringDecoder stringDecoder = new StringDecoder();
registry.bind("length-decoder", lengthDecoder);
registry.bind("string-decoder", stringDecoder);

LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4);
StringEncoder stringEncoder = new StringEncoder();
registry.bind("length-encoder", lengthEncoder);
registry.bind("string-encoder", stringEncoder);

List<ChannelHandler> decoders = new ArrayList<ChannelHandler>();
decoders.add(lengthDecoder);
decoders.add(stringDecoder);

List<ChannelHandler> encoders = new ArrayList<ChannelHandler>();
encoders.add(lengthEncoder);
encoders.add(stringEncoder);

registry.bind("encoders", encoders);
registry.bind("decoders", decoders);

然后你参考encoder/decoder:

from("netty4:tcp://localhost:{{port}}?decoders=#length-decoder,#string-decoder&sync=false")

我建议您先退后一步,运行 使用 textline=true 和 allowDefaultCodec=false 的 netty 流只是为了查看您的 netty 通信是否正常。然后交encoder/decoder部分。

创建一个 SimpleRegistry 并将其传递给 CamelContext:

SimpleRegistry simpleRegistry = new SimpleRegistry();
simpleRegistry.put("stringEncoder", new StringEncoder());
simpleRegistry.put("stringDecoder", new StringDecoder());
CamelContext context = new DefaultCamelContext(simpleRegistry);