首页  >  文章  >  后端开发  >  Apache Mina 学习笔记(4)-Session

Apache Mina 学习笔记(4)-Session

黄舟
黄舟原创
2017-01-18 09:59:431268浏览

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的状态转换关系:

313.png

以下几个参数可以用来配置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/sent
number of messages received/sent
Idle status
throughput

and many other useful informations.

Handler

最后,同样重要的是,一个Handler要附着于一个Session上,用来处理程序的消息。这个Handler也会发送包作为回应,只要简单的调用write方法即可:

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

以上就是Apache Mina 学习笔记(4)-Session的内容,更多相关内容请关注PHP中文网(www.php.cn)!


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn