简体   繁体   中英

Apache camel netty custom encoder and decoder sample

Apache camel netty tcp component doc( http://camel.apache.org/netty.html ) says,

encoder

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

decoder

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

Could you please point me an example on how/what to do in overriding class. I want a custom tcp encoder/decoder to read/write bytes.

This class and it's super class are encoders and you can use it as an example: org.jboss.netty.handler.codec.string.StringEncoder

There are other classes used in the examples on the netty page from the "Using multiple codecs" heading which you can look at the source code for to see how they use the interface.

Failing that it's best to look at the netty project and look at the unit tests for the encoders.

In the netty documentation there is code for using the ChannelHandler for encoders and decoders. From the documentation:

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);

And then you refer to the encoder/decoder:

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

I would suggest you first take a step back and run your netty flow with textline=true and allowDefaultCodec=false just to see that your netty communication is working. Then hand the encoder/decoder part.

Create a SimpleRegistry and pass it to the CamelContext:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM