ssm基於shiro-redis 實現session共享(已完成遷移)

shiro.xml 配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--shiroRedis start-->
    <bean id="redisManager" class="org.crazycake.shiro.RedisManager">
        <property name="host" value="127.0.0.1"/>
        <property name="port" value="6379"/>
        <property name="expire" value="1800"/>
        <!-- optional properties:
        <property name="timeout" value="10000"/>
        <property name="password" value="123456"/>
        -->
    </bean>

    <!-- redisSessionDAO -->
    <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO">
        <property name="redisManager" ref="redisManager" />
    </bean>

    <!-- sessionManager -->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="sessionDAO" ref="redisSessionDAO" />
        <property name="globalSessionTimeout" value="1800000"/>
        <property name="deleteInvalidSessions" value="true"/>
        <property name="sessionValidationSchedulerEnabled" value="true"/>
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
        <!--<property name="sessionIdCookieEnabled" value="true"/>
        <property name="sessionIdCookie" ref="sessionIdCookie"/>-->
    </bean>

    <!--end-->



    <!-- 緩存管理器-->
    <bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
          p:cacheManager-ref="ehcache"/>

    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
          p:configLocation="classpath:ehcache/ehcache.xml"
          p:shared="true"/>


    <bean id="cacheManager" class="com.bestpay.bigdata.ops.web.SpringCacheManagerWrapper">
        <property name="cacheManager" ref="springCacheManager"/>
    </bean>

    <!-- 憑證匹配器 -->
    <bean id="credentialsMatcher" class="com.bestpay.bigdata.ops.web.credentials.RetryLimitHashedCredentialsMatcher">
        <constructor-arg ref="cacheManager"/>
        <property name="hashAlgorithmName" value="md5"/>
        <property name="hashIterations" value="2"/>
        <property name="storedCredentialsHexEncoded" value="true"/>
    </bean>

    <!-- Realm實現 -->
    <bean id="userRealm" class="com.bestpay.bigdata.ops.web.realm.UserRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
        <property name="cachingEnabled" value="false"/>
        <property name="authenticationCachingEnabled" value="true"/>
        <property name="authenticationCacheName" value="authenticationCache"/>
        <property name="authorizationCachingEnabled" value="true"/>
        <property name="authorizationCacheName" value="authorizationCache"/>

    </bean>

    <!-- 會話ID生成器 -->
    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    <!-- 會話Cookie模板 -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="sid"/>
        <property name="httpOnly" value="true"/>
        <property name="maxAge" value="-1"/>
    </bean>

    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="rememberMe"/>
        <property name="httpOnly" value="true"/>
        <property name="maxAge" value="2592000"/><!-- 30天 -->
    </bean>

    <!-- rememberMe管理器 -->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <!-- rememberMe cookie加密的密鑰 建議每個項目都不一樣 默認AES算法 密鑰長度(128 256 512 位)-->
        <property name="cipherKey"
                  value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>
        <property name="cookie" ref="rememberMeCookie"/>
    </bean>

    <!-- 會話DAO-->
    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    </bean>

    <!-- 會話驗證調度器 -->
    <bean id="sessionValidationScheduler" class="com.bestpay.bigdata.ops.web.support.QuartzSessionValidationScheduler">
        <property name="sessionValidationInterval" value="1800000"/>
        <property name="sessionManager" ref="sessionManager"/>
    </bean>

    <!-- 會話管理器 -->
  <!--  <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="globalSessionTimeout" value="1800000"/>
        <property name="deleteInvalidSessions" value="true"/>
        <property name="sessionValidationSchedulerEnabled" value="true"/>
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
        <property name="sessionDAO" ref="sessionDAO" />
        <property name="sessionIdCookieEnabled" value="true"/>
        <property name="sessionIdCookie" ref="sessionIdCookie"/>
    </bean>-->

    <!--<bean id="sessionManager" class="com.bestpay.bigdata.ops.web.filter.DefaultHeaderSessionManager">
        <property name="sessionDAO" ref="sessionDAO"/>
        <property name="globalSessionTimeout" value="3600000"/>
        <property name="sessionValidationInterval" value="3600000"/>
        <property name="deleteInvalidSessions" value="true"/>
        <property name="sessionValidationSchedulerEnabled" value="true"/>
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
    </bean>-->


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

    <!-- 相當於調用SecurityUtils.setSecurityManager(securityManager) -->
    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
        <property name="arguments" ref="securityManager"/>
    </bean>

    <!-- 基於Form表單的身份驗證過濾器 -->
    <!--  <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
          <property name="loginUrl" value="/logon"/>
      </bean>-->
    <bean id="formAuthenticationFilter" class="com.bestpay.bigdata.ops.web.filter.MyFormAuthenticationFilter">
        <property name="usernameParam" value="username"/>
        <property name="passwordParam" value="password"/>
        <property name="rememberMeParam" value="rememberMe"/>
        <!--<property name="loginUrl" value="/login"/>-->
        <!-- <property name="loginUrl" value="/static/dist/index.html"/>-->
        <property name="loginUrl" value="/login"/>
    </bean>

    <bean id="sysUserFilter" class="com.bestpay.bigdata.ops.web.filter.SysUserFilter"/>
    <bean id="forceLogoutFilter" class="com.bestpay.bigdata.ops.web.filter.ForceLogoutFilter"/>

    <!-- Shiro的Web過濾器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login"/>
        <!-- <property name="loginUrl" value="/static/dist/index.html"/>-->
        <property name="filters">
            <util:map>
                <!--  <entry key="optionFilter" value-ref="shiroUserFilter"/>-->
                <entry key="authc" value-ref="formAuthenticationFilter"/>
                <entry key="sysUser" value-ref="sysUserFilter"/>
                <entry key="forceLogout" value-ref="forceLogoutFilter"/>
            </util:map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                <!--   /getMenus = anon-->
                /ssoLogin/** = anon
                /favicon.ico = anon
                /validateCode = anon
                /api/**=anon
                /validateCode1 = anon
                /static/dist/index.html =anon
                /static/**=anon
                /screen/**=anon
                /bigscreen/** = anon
                /user/addUser = anon
                //tableau/getCount=anon
                /login = authc
                /jsp/** = authc
                /logout = logout
                /authenticated = authc
                /** = forceLogout,user,sysUser

            </value>
        </property>
    </bean>
    <!-- Shiro生命週期處理器-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
</beans>

shiroRedisManager:

package com.bestpay.bigdata.ops.manager.common.cache;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Set;

@Component
@Slf4j
@Getter
@Setter
public class ShiroRedisManager {
    private String host = "127.0.0.1";

    private int port = 6379;

    // 0 - never expire
    private int expire = 0;

    //timeout for jedis try to connect to redis server, not expire time! In milliseconds
    private int timeout = 0;

    private String password = "";

    private static JedisPool jedisPool = null;

    public ShiroRedisManager(){

    }

    /**
     * 初始化方法
     */
    public void init(){
        if(jedisPool == null){
            if(password != null && !"".equals(password)){
                jedisPool = new JedisPool(new JedisPoolConfig(), host, port, timeout, password);
            }else if(timeout != 0){
                jedisPool = new JedisPool(new JedisPoolConfig(), host, port,timeout);
            }else{
                jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
            }

        }
    }

    /**
     * get value from redis
     * @param key
     * @return
     */
    public byte[] get(byte[] key){
        byte[] value = null;
        Jedis jedis = jedisPool.getResource();
        try{
            value = jedis.get(key);
        }finally{
            jedisPool.returnResource(jedis);
        }
        return value;
    }

    /**
     * set
     * @param key
     * @param value
     * @return
     */
    public byte[] set(byte[] key,byte[] value){
        Jedis jedis = jedisPool.getResource();
        try{
            jedis.set(key,value);
            if(this.expire != 0){
                jedis.expire(key, this.expire);
            }
        }finally{
            jedisPool.returnResource(jedis);
        }
        return value;
    }

    /**
     * set
     * @param key
     * @param value
     * @param expire
     * @return
     */
    public byte[] set(byte[] key,byte[] value,int expire){
        Jedis jedis = jedisPool.getResource();
        try{
            jedis.set(key,value);
            if(expire != 0){
                jedis.expire(key, expire);
            }
        }finally{
            jedisPool.returnResource(jedis);
        }
        return value;
    }

    /**
     * del
     * @param key
     */
    public void del(byte[] key){
        Jedis jedis = jedisPool.getResource();
        try{
            jedis.del(key);
        }finally{
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * flush
     */
    public void flushDB(){
        Jedis jedis = jedisPool.getResource();
        try{
            jedis.flushDB();
        }finally{
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * size
     */
    public Long dbSize(){
        Long dbSize = 0L;
        Jedis jedis = jedisPool.getResource();
        try{
            dbSize = jedis.dbSize();
        }finally{
            jedisPool.returnResource(jedis);
        }
        return dbSize;
    }

    /**
     * keys
     * @param
     * @return
     */
    public Set<byte[]> keys(String pattern){
        Set<byte[]> keys = null;
        Jedis jedis = jedisPool.getResource();
        try{
            keys = jedis.keys(pattern.getBytes());
        }finally{
            jedisPool.returnResource(jedis);
        }
        return keys;
    }


    public void setPassword(String password) {
        this.password = password;
    }

}

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章