2012-04-23 27 views
0

我回顧了Netty的文檔,發現在示例的源類中的一些評論:org.jboss.netty.example.factorial.FactorialServerHandler,在這種SRC,一些意見:狀態xxxServerHandle和unstateful yyyServerhandle之間的區別?

//##in org.jboss.netty.example.factorial.FactorialServerPipelineFactory 
    ...... 
    // and then business logic. 
    // Please note we create a handler for every new channel 
    // because it has stateful properties. 
    pipeline.addLast("handler", new FactorialServerHandler()); 

但是,我重新檢查其他的例子,比如作爲TelnetServerPipelineFactory,似乎沒有什麼區別,手柄是創建:

// and then business logic. 
    pipeline.addLast("handler", new TelnetServerHandler()); 

所有的處理程序與「新」的管道產生的? Netty中的所有例子都是有狀態的?顯然Echo/Telnet不需要保留有狀態的道具。

在我的老項目中,我使用了Netty創建一個Http Server充當REST風格的服務器,我的處理程序代碼是:

public class HttpServerPipelineFactory implements ChannelPipelineFactory { 
     private final HttpServerHandler handler; 
     public ChannelPipeline getPipeline() throws Exception { 
      ChannelPipeline pipeline = pipeline(); 
      pipeline.addLast("decoder", new HttpRequestDecoder()); 
      pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); 
      pipeline.addLast("encoder", new HttpResponseEncoder()); 
      pipeline.addLast("handler", handler); //singleton 
      return pipeline; 
     } 
    } 

我的REST風格的服務器是statefulless(這是REST含義之一),所以我用單身手柄。我是對的嗎?

回答

1

當文檔說「有狀態」,則意味着該狀態信息被存儲爲在的ChannelHandler字段,因此,其不可能不同頻道之間共享的ChannelHandler。如果您沒有將狀態信息存儲爲字段,則可以將其用作Singelton。

0

你沒有理由來實例化新的處理程序,如果他們是無狀態的。但是,在HTTP中的例子那些處理狀態。他們從網絡逐幀接收數據,並將它們解析爲標題和不包含的內容。然後,如果請求被分塊,聚合是合併塊爲單一的有效載荷,等等,總之,除非你正在建設一個回聲服務器,較低級別的處理程序可能必須是有狀態的,但更高級別不需要。