通过复写 shiro 的 SessionDAO 以实现将 session 保存到 redis 集群中

8,820 阅读4分钟
原文链接: www.zifangsky.cn

如题所示,在分布式系统架构中需要解决的一个很重要的问题就是——如何保证各个应用节点之间的Session共享。现在通用的做法就是使用redis、memcached等组件独立存储所有应用节点的Session,以达到各个应用节点之间的Session共享的目的

在Java Web项目中实现session共享的一个很好的解决方案是:Spring Session+Spring Data Redis。关于这方面的内容可以参考我之前写的这篇文章:www.zifangsky.cn/862.html

但是,如果在项目中使用到了shiro框架,并且不想使用Spring Session的话,那么我们可以通过重载shiro的SessionDAO同样达到将shiro管理的session保存到redis集群的目的,以此解决分布式系统架构中的session共享问题

下面,我将详细说明具体该如何来实现:

(1)配置Spring Data Redis环境:

关于Spring Data Redis环境的配置可以参考我之前的这篇文章:www.zifangsky.cn/861.html

在这里,我测试使用的是redis集群模式,当然使用redis单节点也可以

(2)复写shiro的SessionDAO:

Java
package cn.zifangsky.shiro;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

@Repository("customShiroSessionDao")
public class CustomShiroSessionDao extends EnterpriseCacheSessionDAO {

    @Resource(name="redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 创建session,保存到redis集群中
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        System.out.println("sessionId: " + sessionId);
        
        BoundValueOperations<String, Object> sessionValueOperations = redisTemplate.boundValueOps("shiro_session_" + sessionId.toString());
        sessionValueOperations.set(session);
        sessionValueOperations.expire(30, TimeUnit.MINUTES);
        
        return sessionId;
    }

    /**
     * 获取session
     * @param sessionId
     * @return
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        
        if(session == null){
            BoundValueOperations<String, Object> sessionValueOperations = redisTemplate.boundValueOps("shiro_session_" + sessionId.toString());
            session = (Session) sessionValueOperations.get();
        }
        
        return session;
    }

    /**
     * 更新session
     * @param session
     */
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        
        BoundValueOperations<String, Object> sessionValueOperations = redisTemplate.boundValueOps("shiro_session_" + session.getId().toString());
        sessionValueOperations.set(session);
        sessionValueOperations.expire(30, TimeUnit.MINUTES);
    }

    /**
     * 删除失效session
     */
    @Override
    protected void doDelete(Session session) {
        redisTemplate.delete("shiro_session_" + session.getId().toString());
        super.doDelete(session);
    }

}

具体含义可以参考注释,这里就不多做解释了

(3)在shiro的配置文件中添加sessionManager:

XHTML
    <!-- 使用redis存储管理session -->
    <bean id="sessionManager"  
        class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 
        <!-- 删除失效session -->
        <property name="sessionValidationSchedulerEnabled" value="true" />  
        <!-- session失效时间(毫秒) --> 
        <property name="globalSessionTimeout" value="1800000" />
        <property name="sessionDAO" ref="customShiroSessionDao" />  
    </bean>

然后在securityManager中使用该sessionManager:

XHTML
   <!-- Shiro安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="customRealm" />
        <property name="sessionManager" ref="sessionManager" />
        <property name="cacheManager" ref="cacheManager" />
    </bean>

注:完整的shiro的配置文件如下:

XHTML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop">
    <description>Shiro 配置</description>
    
    <context:component-scan base-package="cn.zifangsky.manager.impl" />
    <context:component-scan base-package="cn.zifangsky.shiro" />
    
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManager" ref="cacheManagerFactory" />
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" />
    </bean>
    
    <!-- 使用redis存储管理session -->
    <bean id="sessionManager"  
        class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 
        <!-- 删除失效session -->
        <property name="sessionValidationSchedulerEnabled" value="true" />  
        <!-- session失效时间(毫秒) --> 
        <property name="globalSessionTimeout" value="1800000" />
        <property name="sessionDAO" ref="customShiroSessionDao" />  
    </bean>
    
    <!-- Shiro安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="customRealm" />
        <property name="sessionManager" ref="sessionManager" />
        <property name="cacheManager" ref="cacheManager" />
    </bean>
    
    <!-- 自定义Realm -->
    <bean id="customRealm" class="cn.zifangsky.shiro.CustomRealm" />
    
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/user/user/login.html" />
        <!-- <property name="successUrl" value="/login/loginSuccessFull" /> -->
        <property name="unauthorizedUrl" value="/error/403.jsp" />
        <!-- <property name="filters">
            <map>
                <entry key="auth" value-ref="userFilter"/>
            </map>  
        </property> -->
        <property name="filterChainDefinitions">
            <value>
                /error/* = anon
                /scripts/* = anon
                /user/user/check.html = anon
                /user/user/verify.html = anon
                /user/user/checkVerifyCode.html = anon
                /user/user/logout.html = logout
                /**/*.htm* = authc
        /**/*.json* = authc
            </value>
        </property>
    </bean>
    
    <!-- <bean id="cleanFilter" class="cn.zifangsky.shiro.CleanFilter"/> -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>

(4)测试:

i)本地简单测试:

将同一项目部署到本地两个不同端口的Tomcat中,然后在其中一个Tomcat登录,接着直接在另一个Tomcat上访问登录后的URL,观察是否可以直接访问还是跳转到登录页面

ii)完整分布式环境测试:

首先将测试项目部署到两个服务器上的Tomcat中,我这里的访问路径分别是:

  • 192.168.1.30:9080
  • 192.168.1.31:9080

接着配置nginx访问(PS:nginx所在IP是:192.168.1.31):

Shell
server {
    server_name  localhost;
    listen 7888;
     
    location /WebSocketDemo
        {       
              proxy_redirect off;
              proxy_set_header        Host $host:7888;
              proxy_set_header        X-Real-IP $remote_addr;
              proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_pass http://demo/WebSocketDemo;
              proxy_set_header   Cookie $http_cookie;
        }

    #access_log  on;
    limit_conn perip 1000;  #同一ip并发数为50,超过会返回503
    access_log logs/access_test.log zifangsky_log;
 }

对应的upstream是:

upstream demo {
  server 192.168.1.30:9080;
  server 192.168.1.31:9080;
}

从上面可以看出,这里设置的nginx的负载均衡策略是默认策略——轮询

最后在浏览器中访问:http://192.168.1.31:7888/WebSocketDemo/user/user/login.html

登录之后,不断刷新页面并观察nginx的日志:

可以发现,经过nginx的反向代理之后,虽然每次访问的实际服务地址都不一样,但是我们的登录状态并没有丢失——并没有跳转到登录页面。这就证明了这个测试小集群的session的确实现了共享,也就是说session保存到了redis集群中,并不受具体的业务服务器的更改而发生改变

当然,我们也可以登录到redis集群,查询一下该sessionId对应的session值:

参考: