2012-11-06 42 views
1

服務器處理程序。對於每個收到的消息,都會有多個響應。業務邏輯涉及將請求放入隊列中,從隊列中移除,處理請求並進行響應。服務器處理程序的Netty異步響應

如何異步處理請求,在保持隊列完整性的同時進行異步響應?

下面的代碼行爲是同步的。

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

回答

1

netty寫入總是異步的,但寫入同一通道的消息將按順序排隊。在閱讀時,如果需要異步操作,則需要將ExecutionHandler添加到ChannelPipeline。如果訂購很重要,請使用OrderedMemoryAwareThreadPoolExecutor實施。您需要在自己的TestHandler之前將其添加到ChannelPipeline。新的Netty 4 API可以更好地控制異步管道處理程序,但它仍在開發中。