首頁  >  文章  >  後端開發  >  Apache Mina 學習筆記(4)-Session

Apache Mina 學習筆記(4)-Session

黄舟
黄舟原創
2017-01-18 09:59:431285瀏覽

Session是Apache的核心,每當一個客戶端連線到達時,就會有一個新的Session被創建,直到該連線關閉。 Session被用來保存連接,以及各種資訊。

Session有以下幾種狀態:

Connected : the session has been created and is available
Idle : the session hasn't processed any request for at least a period of time (this period is configurable)

Idle for read : no read has actually been made for a period of time
Idle for write : no write has actually been made for a period of time
Idle for both : no read nor write for a period of time

Closing : the session is being closed (the remaining messages are being flushed, cleaning up is not terminated)
Closed : The session is now closed, nothing else can be done to revive it.

下圖表示Session的狀態轉換關係:

Apache Mina 學習筆記(4)-Session

以下幾個參數可以用來設定Session

receive buffer sizesize

管理用戶自訂的屬性:

例如,如果你想追蹤一個用戶從會話被建立之後發送了多少個請求,那麼它可以很容易存入這種映射:只要創建一個key關聯到value就行。

...  
int counterValue = session.getAttribute( "counter" );  
session.setAttribute( "counter", counterValue + 1 );  
...

我們採用key/value 對的方式儲存屬性到會話中,這種key/value對可以透過session的容器讀取,添加或刪除。

定義container


正如我們所說,這個容器是一個key/value容器,預設是一種映射,當然也可以定義成其他的資料結構。當Session被創建時我們可以實作一個介面和一個factory用來建立容器。下面的程式碼片段範例了在Session初始化時如何建立容器(看不懂,這個到底什麼意思?)

protected final void initSession(IoSession session,  
        IoFuture future, IoSessionInitializer sessionInitializer) {  
    ...  
    try {  
        ((AbstractIoSession) session).setAttributeMap(session.getService()  
                .getSessionDataStructureFactory().getAttributeMap(session));  
    } catch (IoSessionInitializationException e) {  
        throw e;  
    } catch (Exception e) {  
        throw new IoSessionInitializationException(  
                "Failed to initialize an attributeMap.", e);  
    }

and here is the factory interface we can implement if we want to define another kind of container :
public interface IoSessionDataStructureFactory {  
    /** 
     * Returns an {@link IoSessionAttributeMap} which is going to be associated 
     * with the specified <tt>session</tt>.  Please note that the returned 
     * implementation must be thread-safe. 
     */  
     IoSessionAttributeMap getAttributeMap(IoSession session) throws Exception;  
 }

Each session also keep a track of records about what has been done for the session :

number of bytes received/sent
number of messages received/sent
Idle status
throughput

and many other useful informations.

Handler

過濾鏈

每個會話會關聯一些過濾鏈,用來處理到來的請求或出去的資料。每個會話都會指定單獨的過濾鏈,大多數情況下,我們會用在會話中用很多相同的過濾鏈。

統計

...  
session.write( <your message> );  
...

最後,同樣重要的是,一個Handler要附著於一個Session上,用來處理程序的消息。這個Handler也會發送套件作為回應,只要簡單的呼叫write方法即可:

rrreee

以上就是Apache Mina 學習筆記(4)-Session的內容,更多相關內容請關注PHP中文網(www.php.cn )!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn