Shiro会话管理
Shiro的会话实际和HttpSession是一致的,都是表示客户端和服务器的一次会话。
Shiro提供了完整的企业级会话管理功能,不依赖于底层容器(如web容器tomcat),不管JavaSE还是JavaEE环境都可以使用,提供了会话管理、会话事件监听、会话存储/持久化、容器无关的集群、失效/过期支持、对Web的透明支持、SSO单点登录的支持等特性。
所以即使没有web服务器,没有Tomcat,Shiro也照样可以使用session。
会话相关的API


会话监听器
会话监听器用于监听会话创建、过期及停止事件。

实际上,在web层(Handler层)建议大家使用原生的HttpSession。那么shiro session有什么意义呢?在传统的web应用里面我们没办法在service里面访问HttpSession,我们也不建议这样做,因为这样就是侵入式的访问了(顶层API在service不能访问)。但是现在有了shiro session我们就可以访问了。
在Handler层使用HttpSession,在service层可以使用shiro提供的session,这样有个好处:即便在service层,也可以访问到session数据。


控制台打印结果说明了shiro提供的session也可以访问到HttpSession中的数据:

SessionDao
SessionDao可以把session存到数据库里面,然后对session进行层删改查操作。

- AbstractSessionDAO提供了SessionDAO的基础实现,如生成会话ID等
- CachingSessionDAO提供了对开发者透明的会话缓存的功能,需要设置相应的CacheManager
- MemorySessionDAO直接在内存中进行会话维护
- EnterpriseCacheSessionDAO提供了缓存功能的会话维护,默认情况下使用MapCache实现,内部使用ConcurrentHashMap保存缓存的会话
使用示例
数据表
create table sessions(
id varchar(200),
session varchar(2000),
constraint pk_sessions primary key(id)
)charset=utf8 ENGINE=InnoDB
配置文件

encache.xml

MySessionDao
注意:需要对session序列化

SerializableUtils

会话验证
Shiro提供了会话验证调度器,用于定期的验证会话是否已过期,如果过期将停止会话。
出于性能考虑,一般情况下都是获取会话时来验证会话是否过期并停止会话的;但是如果在web环境中,如果用户不主动退出是不知道会话是否过期的,因此需要定期的检测会话是否过期,Shiro提供了会话验证调度器SessionValidationScheduler。
Shiro也提供了使用Quartz会话验证调度器:QuartzSessionValidationScheduler。
网友评论