title: springrain技术详解(5)-shiro的httpSession CreateTime: 2013-12-20 10:49:00 UpdateTime: 2013-12-20 10:49:00 CategoryName: web --- --- title: "springrain技术详解(5)-shiro的httpSession" date: 2013-12-20T10:49:00+08:00 draft: false tags: ["springrain"] categories: ["web"] author: "springrain" --- ## shiro的cacheManager shiro通过扩展cacheManager实现自定义缓存,sessionDao可以把httpSession存储到cache中.shiro默认提供的EnterpriseCacheSessionDAO已经非常强大,EnterpriseCacheSessionDAO使用cacheManager,把httpSession存储到缓存中. 对于web项目,shiro通过门面模式已经复写了servlet的request,reponse和session,也就是说,web项目自己管理httpSession,和容器无关!这样我们就能很容易的实现分布式的session共享. springrain使用了shiro的EnterpriseCacheSessionDAO,如果是单机情况,使用shiro自带的MemoryConstrainedCacheManager就足够了,如果是集群共享,就需要扩展实现cacheManager把httpSession存储到独立的缓存服务器,例如springrain使用了redis缓存服务器. ## redis扩展实现 扩展sessionManager的同时,也需要扩展实现shiro的ICache接口,也就是具体的缓存实现. 例如springrain的扩展实现 [ShiroRedisCacheManager](https://gitee.com/chunanyong/springrain/blob/SpringRainV4.0.0/src/main/java/org/springrain/frame/shiro/ShiroRedisCacheManager.java) 和 [ShiroRedisCache](https://gitee.com/chunanyong/springrain/blob/SpringRainV4.0.0/src/main/java/org/springrain/frame/shiro/ShiroRedisCache.java). 基本原理就是web应用创建,修改,读取,销毁httpSession都是通过web应用的cacheManager实现,web容器(例如tomcat)不再处理httpSession相关操作. 在springrain中,redis相当于一个缓存数据库,多个web应用同时连接,这样实现httpSession共享,负载均衡. ## 场景案例 springrain部署到5个tomat实例,前端通过nginx配置集群负载,tomat1突然宕机,原来tomcat1的用户分配到tomcat2上,tomcat2根据sessionId从cacheManger中查询到了相应的httpSession,这样tomcat就可以直接处理业务,前台用户的操作不会造成影响.