Apache MINA 框架之Session介绍

Session是NIMA的核心,每一次客户端连接到服务器将创建一个新的session,它将保存在内存中,知道客户端断开连接。

Session State

  • Connected : session创建成功并有效
  • Idle : 闲置状态
    • Idle for read : 一段时间内没有读操作;
    • Idle for write : 段时间内没有写操作;
    • Idle for both : 段时间内既没有读也没有写操作;
  • Closing : session正在关闭状态;
  • Closed : session关闭状态;

 

session状态转换图:

 

 

session配置:

不同参数的配置可以组合成一个特定的session

  • receive buffer size
  • sending buffer size
  • Idle time
  • Write timeOut

 

管理用户自定义属性:

将来可能使用的一些数据可以储存在session中,通过key-value键值对存储,例如:你想知道用户连接的数量:

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

 

这样,我们通过在session对属性的key/value进行增删改读的基本操作,实现对自定义属性的处理。

 

定义容器:

容器已key-value键值对存储,默认使用map,但是也可以定义为另外的数据结构如果想处理长时间存活的数据或者避免内存过大。我们可以通过实现接口或工厂的方式在创建session的时候创建好容器。

创建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);
    }
    ...

通过工厂接口实现其他数据结构容器:

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

 

过滤链(Filter chain):

每个session都关联一个过滤链,处理连接请求,发送或接受。可以通过session动态的修改和管理过滤链。

 

统计:

每个session可以跟踪session记录:

  • 发送/接受的字节数
  • 接受/发送的信息数
  • 闲置状态
  • 吞吐量

等等之类有用的信息....

 

Handler(处理器)

每个session至少依附于一个Handler上,应用程序通过调用session的write()方法发送响应包:

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

 

转载于:https://www.cnblogs.com/quyongjin/archive/2013/06/14/3135754.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值