Reputation: 411
A server handler. For each received message, there will be multiple responses. Business Logic involves putting the requests in a queue, removing from the queue, processing the requests and responding.
How do i process requests asynchronously, respond asynchronously while maintaining the integrity of the queue?
The code below is behaves synchronously.
public class TestHandler extends SimpleChannelHandler {
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
// Send greeting for a new connection.
e.getChannel().write(
"Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
e.getChannel().write("It is " + new Date() + " now.\r\n");
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
String XMLFromClient = (String) e.getMessage() ;
ReadXML2 rx = new ReadXML2();
String response = null;
response = rx.processInput(XMLFromClient);
ChannelFuture future = e.getChannel().write(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getCause().printStackTrace();
Channel ch = e.getChannel();
ch.close();
}
}
Upvotes: 3
Views: 3356
Reputation: 9061
In netty writes are always asynchronous, but messages written to the same channel will be queued up in sequence. While reading, if you want asynchronous operation then you need to add an ExecutionHandler to the ChannelPipeline
. If ordering is important then use the the OrderedMemoryAwareThreadPoolExecutor implementation. You need to add it to the ChannelPipeline
ahead of your own TestHandler
. The new Netty 4 API provides better control over async pipeline handlers, but it is still under development.
Upvotes: 2