Session是Apache的核心,每當一個用戶端串連到達時,就會有一個新的Session被建立,直到該串連關閉。Session被用來儲存串連,以及各種資訊。
Session有如下幾種狀態:
Connected : the session has been created and is availableIdle : 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 timeIdle for write : no write has actually been made for a period of timeIdle for both : no read nor write for a period of timeClosing : 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的狀態轉換關係:
以下幾個參數可以用來配置Session
receive buffer size
sending buffer size
Idle time
Write timeOut
系統管理使用者自訂的屬性:
例如,如果你想跟蹤一個使用者從會話被建立之後發送了多少個請求,那麼它可以很容易存入這種映射:只要建立一個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/sentnumber of messages received/sentIdle statusthroughputand many other useful informations.Handler
最後,同樣重要的是,一個Handler要附著於一個Session上,用來處理常式的訊息。這個Handler也會發送包作為回應,只要簡單的調用write方法即可:
... session.write( <your message> ); ...
以上就是Apache Mina 學習筆記(4)-Session的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!