简体   繁体   中英

Using netty with business logic

I'm not too experienced using netty and have a question about the documentation of ChannelPipeline . Here is what it is about exactly:

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

I don't quite understand the MyBusinessLogicHandler class. Should it implement DuplexChannelHandler or something different? For instance, in my particular case I have the following class:

public class Packet{}

I want to decode some byte sequence into Packet , give to MyBusinessLogicHandler which produces some Packet . and then encode it into a byte stream again to send back to a client. I currently see it like this:

public class MyBusinessLogicHandler extends SimpleChannelInboundHandler<MyModel>{
    public void channelRead0(ChannelHandlerContext ctx, Packet msg){
         Packet rslt = null;
         //Do some complicated business logic
         ctx.write(rslt);
    }
}

I'm not sure if it's a common way to do things in netty. Can you clarify please?

Yeap. That's totally fine and correct way for implementing MyBusinessLogicHandler . You don't need DuplexChannelHandler as in your pipeline you have already MyProtocolEncoder (that I suppose implements ChannelOutboundHandler ). So when you call ctx.write(rslt) you trigger write event for outbound handlers.

DuplexChannelHandler would be useful only in case you would like to implement both encoder and decoder in the same class. For example, you may do that by joining MyProtocolEncoder and MyProtocolDecoder .

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