Apache Shiro 分布式架构下Redis实现Session 的共享

转载地址:https://blog.csdn.net/yr_xiaozheng/article/details/79556137

参考资料:http://blog.csdn.net/lishehe/article/details/45223823

写的非常棒,只是缺少了几个工具类,我在这里给出了自己的代码,方便用到。


1.  redis.properties

[java]  view plain  copy
  1. redis.host=127.0.0.1  
  2. redis.port=6379  
  3. redis.default.db=2  
  4. redis.timeout=100000  
  5. redis.maxIdle=100  
  6. redis.maxWaitMillis=30000  
  7. redis.testOnBorrow=true  


2. applicationContext-shiro.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
  5.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  6.         <!--配置 session 管理-->  
  7.         <property name="sessionManager" ref="sessionManager"/>  
  8.         <!--配置 记住我-->  
  9.         <property name="rememberMeManager" ref="rememberMeManager"/>  
  10.         <!-- 配置多个Realm的登录认证 -->  
  11.         <property name="authenticator" ref="authenticator"/>  
  12.         <!-- 配置多个Realm的权限认证 -->  
  13.         <property name="authorizer" ref="authorizer"/>  
  14.   
  15.   
  16.         <!-- redis缓存 -->  
  17.         <property name="cacheManager" ref="redisCacheManager" />  
  18.     </bean>  
  19.   
  20.     <!--配置多个 realm 的权限权限认证-->  
  21.     <bean id="authorizer" class="org.apache.shiro.authz.ModularRealmAuthorizer">  
  22.         <property name="realms">  
  23.             <list>  
  24.                 <!--这个实现权限匹配的方法-->  
  25.                 <ref bean="myRealm"/>  
  26.             </list>  
  27.         </property>  
  28.     </bean>  
  29.   
  30.     <!-- 配置多个Realm -->  
  31.     <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">  
  32.   
  33.         <!--验证的时候,是用迭代器,所以可以认为验证的顺序就是这个 list 的顺序-->  
  34.         <property name="realms">  
  35.             <list>  
  36.                 <!--<ref bean="otherRealm"/>-->  
  37.                 <ref bean="myRealm"/>  
  38.             </list>  
  39.         </property>  
  40.         <property name="authenticationStrategy">  
  41.   
  42.             <!--所有 realm 认证通过才算登录成功-->  
  43.             <!--<bean id="authenticationStrategy" class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/>-->  
  44.             <!--验证某个 realm 成功后直接返回,不会验证后面的 realm 了-->  
  45.             <bean id="authenticationStrategy" class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"/>  
  46.             <!--所有的 realm 都会验证,其中一个成功,也会继续验证后面的 realm,最后返回成功-->  
  47.             <!--<bean id="authenticationStrategy" class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"/>-->  
  48.         </property>  
  49.     </bean>  
  50.   
  51.     <!--自定义 MyRealm,登录的认证入口 ,需要继承AuthorizingRealm,项目中会体现-->  
  52.     <bean id="myRealm" class="com.tms.shiro.MyRealm">  
  53.         <!-- 配置密码匹配器 -->  
  54.         <property name="credentialsMatcher">  
  55.             <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">  
  56.                 <!-- 加密算法为SHA-256 -->  
  57.                 <property name="hashAlgorithmName" value="SHA-256"/>  
  58.                 <!-- 加密迭代次数 -->  
  59.                 <property name="hashIterations" value="1024"/>  
  60.                 <!--是否存储散列后的密码为16进制,为 true:.toHex(),为 false:.toBase64()-->  
  61.                 <property name="storedCredentialsHexEncoded" value="false"/>  
  62.             </bean>  
  63.         </property>  
  64.     </bean>  
  65.   
  66.     <!--rememberMeManager管理 配置-->  
  67.     <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">  
  68.         <property name="cookie">  
  69.             <bean class="org.apache.shiro.web.servlet.SimpleCookie">  
  70.                 <!--设置超时时间 单位 秒,一天=86400-->  
  71.                 <constructor-arg value="shiro-cookie"/>  
  72.                 <property name="maxAge" value="86400"/>  
  73.                 <property name="httpOnly" value="true"/>  
  74.             </bean>  
  75.         </property>  
  76.     </bean>  
  77.   
  78.     <!--session管理 配置-->  
  79.     <!--<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">-->  
  80.     <!--<bean id="sessionManager" class="com.tms.shiro.SessionManager">  
  81.         <!–session 过期时间 单位 毫秒,2400000=40min>  
  82.         <property name="globalSessionTimeout" value="2400000"/>  
  83.   
  84.         <!–有需要可以自行配置–>  
  85.         <!–<property name="cacheManager" ref="xxxx"></property>>  
  86.         <!–有需要可以自行配置–>  
  87.         <!–<property name="sessionDAO" ref="xxx"></property>>  
  88.   
  89.         <property name="sessionIdCookie" ref="sessionIdCookie"/>  
  90.     </bean>-->  
  91.   
  92.     <!-- 自定义sessionId 防止同tomcat 等容器冲突 -->  
  93.     <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
  94.         <constructor-arg value="token"/>  
  95.         <property name="maxAge" value="86400"/>  
  96.         <property name="path" value="/"/>  
  97.   
  98.     </bean>  
  99.   
  100.     <!--shiro 请求拦截器,这里的 bean id 一定要对应 web.xml 中的filter-name,否则找不到这个拦截器-->  
  101.     <bean id="shiroFilter" class="com.tms.shiro.MyShiroFilterFactoryBean">  
  102.         <property name="securityManager" ref="securityManager"/>  
  103.         <!--登录地址-->  
  104.         <property name="loginUrl" value="login"/>  
  105.         <!--登录成功跳转的地址-->  
  106.         <property name="successUrl" value="/userAction_findList"/>  
  107.         <!--权限认证失败跳转的地址-->  
  108.         <property name="unauthorizedUrl" value="error"/>  
  109.         <!--需要权限拦截的路径-->  
  110.         <property name="filterChainDefinitions">  
  111.             <value>  
  112.                 <!--/login = anon-->  
  113.                 <!--/validateCode = anon-->  
  114.                 <!--/** = authc-->  
  115.             </value>  
  116.         </property>  
  117.     </bean>  
  118.   
  119.     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 ,不明觉厉,没有深究-->  
  120.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
  121.   
  122.   
  123.   
  124.   
  125.   
  126.   
  127.   
  128.     <!-- 自定义redisManager-redis -->  
  129.     <bean id="redisCacheManager" class="com.tms.util.redis.RedisCacheManager">  
  130.         <property name="redisManager" ref="redisManager" />  
  131.     </bean>  
  132.     <!-- 自定义cacheManager -->  
  133.     <bean id="redisCache" class="com.tms.util.redis.RedisCache">  
  134.         <constructor-arg ref="redisManager"></constructor-arg>  
  135.     </bean>  
  136.   
  137.     <bean id="redisManager" class="com.tms.util.redis.RedisManager"></bean>  
  138.   
  139.     <!-- session会话存储的实现类 -->  
  140.     <bean id="redisShiroSessionDAO" class="com.tms.util.redis.RedisSessionDao">  
  141.         <property name="redisManager" ref="redisManager" />  
  142.     </bean>  
  143.   
  144.     <!-- session管理器 -->  
  145.     <bean id="sessionManager"  
  146.           class="com.tms.shiro.SessionManager">  
  147.         <!-- 设置全局会话超时时间,默认30分钟(1800000) -->  
  148.         <property name="globalSessionTimeout" value="1800000" />  
  149.         <!-- 是否在会话过期后会调用SessionDAO的delete方法删除会话 默认true -->  
  150.         <property name="deleteInvalidSessions" value="true" />  
  151.   
  152.         <!-- 会话验证器调度时间 -->  
  153.         <property name="sessionValidationInterval" value="1800000" />  
  154.   
  155.         <!-- session存储的实现 -->  
  156.         <property name="sessionDAO" ref="redisShiroSessionDAO" />  
  157.         <!-- sessionIdCookie的实现,用于重写覆盖容器默认的JSESSIONID -->  
  158.         <property name="sessionIdCookie" ref="sharesession" />  
  159.         <!-- 定时检查失效的session -->  
  160.         <property name="sessionValidationSchedulerEnabled" value="true" />  
  161.     </bean>  
  162.   
  163.     <!-- sessionIdCookie的实现,用于重写覆盖容器默认的JSESSIONID -->  
  164.     <bean id="sharesession" class="org.apache.shiro.web.servlet.SimpleCookie">  
  165.         <!-- cookie的name,对应的默认是 JSESSIONID -->  
  166.         <constructor-arg name="name" value="SHAREJSESSIONID" />  
  167.         <!-- jsessionId的path为 / 用于多个系统共享jsessionId -->  
  168.         <property name="path" value="/" />  
  169.         <property name="httpOnly" value="true"/>  
  170.     </bean>  
  171.   
  172.   
  173.     <!-- shiro的自带缓存管理器encahe -->  
  174.     <!-- <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> -->  
  175.     <!-- <property name="cacheManagerConfigFile" value="classpath:config/ehcache-shiro.xml"  
  176.         /> -->  
  177.     <!-- </bean> -->  
  178.   
  179.     <!-- 开启shiro的注解,需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->  
  180.     <bean  
  181.             class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
  182.             depends-on="lifecycleBeanPostProcessor"></bean>  
  183.     <bean  
  184.             class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  185.         <property name="securityManager" ref="securityManager" />  
  186.     </bean>  
  187.   
  188. </beans>  



3. redis.xml


[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.         http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.  http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
  9.   
  10.     <!-- 加载Reids属性配置文件 ignore-unresolvable="true"-->  
  11.     <context:property-placeholder  
  12.             location="classpath:redis.properties"/>  
  13.   
  14.     <bean id="propertyConfigurerRedis"  
  15.           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  16.         <property name="order" value="1"/>  
  17.         <property name="ignoreUnresolvablePlaceholders" value="true"/>  
  18.         <property name="systemPropertiesMode" value="1"/>  
  19.         <property name="searchSystemEnvironment" value="true"/>  
  20.         <property name="locations">  
  21.             <list>  
  22.                 <value>classpath:redis.properties</value>  
  23.             </list>  
  24.         </property>  
  25.     </bean>  
  26.   
  27.     <!--支持缓存注释, 使用key生成器-->  
  28.     <bean id="redisCacheKeyGenerator" class="com.tms.util.redis.CustomRedisCacheKeyGenerator"/>  
  29.     <cache:annotation-driven key-generator="redisCacheKeyGenerator"/>  
  30.   
  31.   
  32.     <!-- 配置redis池,最大空闲实例数,(创建实例时)最大等待时间,(创建实例时)是否验证 -->  
  33.     <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  34.         <property name="maxIdle" value="${redis.maxIdle}"/>  
  35.         <property name="testOnBorrow" value="${redis.testOnBorrow}"/>  
  36.         <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>  
  37.         <property name="minEvictableIdleTimeMillis" value="300000"/>  
  38.         <property name="numTestsPerEvictionRun" value="3"/>  
  39.         <property name="timeBetweenEvictionRunsMillis" value="6000"/>  
  40.     </bean>  
  41.   
  42.     <bean id="jedisConnectionFactory"  
  43.           class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
  44.         <property name="usePool" value="true"></property>  
  45.         <property name="hostName" value="${redis.host}"/>  
  46.         <property name="port" value="${redis.port}"/>  
  47.         <property name="timeout" value="${redis.timeout}"/>  
  48.         <property name="database" value="${redis.default.db}"></property>  
  49.   
  50.         <property name="poolConfig" ref="jedisPoolConfig"></property>  
  51.     </bean>  
  52.   
  53.     <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
  54.         <property name="connectionFactory" ref="jedisConnectionFactory"></property>  
  55.         <property name="keySerializer">  
  56.             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>  
  57.         </property>  
  58.         <property name="valueSerializer">  
  59.             <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
  60.         </property>  
  61.     </bean>  
  62.   
  63.     <!--V2 配置cacheManager, 使用默认的 用户自定义的 RedisCacheManager  -->  
  64.     <bean id="cacheManager" class="com.tms.util.redis.CustomizedRedisCacheManager">  
  65.         <constructor-arg ref="jedisTemplate"/>  
  66.         <!--使用前缀,使用以后,以cache的value作为redis中的namespace,缓存的键也会加入这个前缀-->  
  67.         <property name="usePrefix" value="true"/>  
  68.   
  69.         <!-- 前缀命名,仅当usePrefix为true时才生效,本例子不使用 -->  
  70.         <!--<property name="cachePrefix">-->  
  71.         <!--<bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">-->  
  72.         <!--<constructor-arg name="delimiter" value=":"/>-->  
  73.         <!--</bean>-->  
  74.         <!--</property>-->  
  75.         <!-- 默认有效期1h ,本例子不使用-->  
  76.         <!--<property name="defaultExpiration" value="3600"/>-->  
  77.     </bean>  
  78.   
  79. </beans>  



4. SerializerUtil.java


[java]  view plain  copy
  1. import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;  
  2.   
  3. /** 
  4.  * @Author: 
  5.  * @Date: 2018-03-13 12:33 
  6.  * @Modified By: 
  7.  * @Description: 
  8.  */  
  9. public class SerializerUtil {  
  10.   
  11.     private static final JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();  
  12.   
  13.     /** 
  14.      * 序列化对象 
  15.      * @param obj 
  16.      * @return 
  17.      */  
  18.     public static <T> byte[] serialize(T obj){  
  19.         try {  
  20.             return jdkSerializationRedisSerializer.serialize(obj);  
  21.         } catch (Exception e) {  
  22.             throw new RuntimeException("序列化失败!", e);  
  23.         }  
  24.     }  
  25.   
  26.     /** 
  27.      * 反序列化对象 
  28.      * @param bytes 字节数组 
  29.      * @param 
  30.      * @return 
  31.      */  
  32.     @SuppressWarnings("unchecked")  
  33.     public static <T> T deserialize(byte[] bytes){  
  34.         try {  
  35.             return (T) jdkSerializationRedisSerializer.deserialize(bytes);  
  36.         } catch (Exception e) {  
  37.             throw new RuntimeException("反序列化失败!", e);  
  38.         }  
  39.     }  
  40.   
  41. }  




5. RedisSessionDao.java


[java]  view plain  copy
  1. import org.apache.shiro.session.Session;  
  2. import org.apache.shiro.session.UnknownSessionException;  
  3. import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;  
  4. import org.slf4j.Logger;  
  5. import org.slf4j.LoggerFactory;  
  6.   
  7. import java.io.Serializable;  
  8. import java.util.Collection;  
  9. import java.util.HashSet;  
  10. import java.util.Set;  
  11.   
  12. /** 
  13.  * @Author: 
  14.  * @Date: 2018-03-13 12:35 
  15.  * @Modified By: 
  16.  * @Description: 
  17.  */  
  18. public class RedisSessionDao extends AbstractSessionDAO {  
  19.   
  20.     private Logger logger = LoggerFactory.getLogger(this.getClass());  
  21.   
  22.     private RedisManager redisManager;  
  23.   
  24.     /** 
  25.      * The Redis key prefix for the sessions 
  26.      */  
  27.     private static final String KEY_PREFIX = "shiro_redis_session:";  
  28.   
  29.     private byte[] getByteKey(String key){  
  30.         return key.getBytes();  
  31.     }  
  32.   
  33.     @Override  
  34.     public void update(Session session) throws UnknownSessionException {  
  35.         this.saveSession(session);  
  36.     }  
  37.   
  38.     @Override  
  39.     public void delete(Session session) {  
  40.         if (session == null || session.getId() == null) {  
  41.             logger.error("session or session id is null");  
  42.             return;  
  43.         }  
  44.         redisManager.del(getByteKey(KEY_PREFIX + session.getId()));  
  45.     }  
  46.   
  47.     @Override  
  48.     public Collection<Session> getActiveSessions() {  
  49.         Set<Session> sessions = new HashSet<Session>();  
  50.         Set<byte[]> keys = redisManager.keys(KEY_PREFIX + "*");  
  51.         if(keys != null && keys.size()>0){  
  52.             for(byte[] key : keys){  
  53.                 Session s = (Session) SerializerUtil.deserialize(redisManager.get(SerializerUtil.deserialize(key)));  
  54.                 sessions.add(s);  
  55.             }  
  56.         }  
  57.         return sessions;  
  58.     }  
  59.   
  60.     @Override  
  61.     protected Serializable doCreate(Session session) {  
  62.         Serializable sessionId = this.generateSessionId(session);  
  63.         this.assignSessionId(session, sessionId);  
  64.         this.saveSession(session);  
  65.         return sessionId;  
  66.     }  
  67.   
  68.     @Override  
  69.     protected Session doReadSession(Serializable sessionId) {  
  70.         if(sessionId == null){  
  71.             logger.error("session id is null");  
  72.             return null;  
  73.         }  
  74.   
  75.         Session s = (Session)redisManager.get(getByteKey(KEY_PREFIX + sessionId));  
  76.         return s;  
  77.     }  
  78.   
  79.     private void saveSession(Session session) throws UnknownSessionException{  
  80.         if (session == null || session.getId() == null) {  
  81.             logger.error("session or session id is null");  
  82.             return;  
  83.         }  
  84.         //设置过期时间  
  85.         long expireTime = 1800000l;  
  86.         session.setTimeout(expireTime);  
  87.         redisManager.setEx(KEY_PREFIX + session.getId(), session, expireTime);  
  88.     }  
  89.   
  90.     public void setRedisManager(RedisManager redisManager) {  
  91.         this.redisManager = redisManager;  
  92.     }  
  93.   
  94.     public RedisManager getRedisManager() {  
  95.         return redisManager;  
  96.     }  
  97.   
  98. }  



6.  RedisManager.java


[java]  view plain  copy
  1. import org.apache.commons.lang3.StringUtils;  
  2. import org.apache.shiro.dao.DataAccessException;  
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.data.redis.connection.RedisConnection;  
  5. import org.springframework.data.redis.core.RedisCallback;  
  6. import org.springframework.data.redis.core.RedisTemplate;  
  7.   
  8. import java.io.Serializable;  
  9. import java.util.Set;  
  10.   
  11. /** 
  12.  * @Author:  
  13.  * @Date: 2018-03-13 12:30 
  14.  * @Modified By: 
  15.  * @Description: 
  16.  */  
  17. public class RedisManager {  
  18.   
  19.     @Autowired  
  20.     private RedisTemplate<Serializable, Serializable> redisTemplate;  
  21.   
  22.     /** 
  23.      * 过期时间 
  24.      */  
  25.   
  26.     /** 
  27.      * 添加缓存数据(给定key已存在,进行覆盖) 
  28.      * @param key 
  29.      * @param obj 
  30.      * @throws DataAccessException 
  31.      */  
  32.     public <T> void set(byte[] key, T obj) throws DataAccessException{  
  33.         final byte[] bkey = key;  
  34.         final byte[] bvalue = SerializerUtil.serialize(obj);  
  35.         redisTemplate.execute(new RedisCallback<Void>() {  
  36.             @Override  
  37.             public Void doInRedis(RedisConnection connection) throws DataAccessException {  
  38.                 connection.set(bkey, bvalue);  
  39.                 return null;  
  40.             }  
  41.         });  
  42.     }  
  43.   
  44.     /** 
  45.      * 添加缓存数据(给定key已存在,不进行覆盖,直接返回false) 
  46.      * @param key 
  47.      * @param obj 
  48.      * @return 操作成功返回true,否则返回false 
  49.      * @throws DataAccessException 
  50.      */  
  51.     public <T> boolean setNX(String key, T obj) throws DataAccessException{  
  52.         final byte[] bkey = key.getBytes();  
  53.         final byte[] bvalue = SerializerUtil.serialize(obj);  
  54.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  55.             @Override  
  56.             public Boolean doInRedis(RedisConnection connection) throws DataAccessException {  
  57.                 return connection.setNX(bkey, bvalue);  
  58.             }  
  59.         });  
  60.   
  61.         return result;  
  62.     }  
  63.   
  64.     /** 
  65.      * 添加缓存数据,设定缓存失效时间 
  66.      * @param key 
  67.      * @param obj 
  68.      * @param expireSeconds 过期时间,单位 秒 
  69.      * @throws DataAccessException 
  70.      */  
  71.     public <T> void setEx(String key, T obj, final long expireSeconds) throws DataAccessException{  
  72.         final byte[] bkey = key.getBytes();  
  73.         final byte[] bvalue = SerializerUtil.serialize(obj);  
  74.         redisTemplate.execute(new RedisCallback<Boolean>() {  
  75.             @Override  
  76.             public Boolean doInRedis(RedisConnection connection) throws DataAccessException {  
  77.                 connection.setEx(bkey, expireSeconds, bvalue);  
  78.                 return true;  
  79.             }  
  80.         });  
  81.     }  
  82.   
  83.     /** 
  84.      * 获取key对应value 
  85.      * @param key 
  86.      * @return 
  87.      * @throws DataAccessException 
  88.      */  
  89.     public <T> T get(final byte[] key) throws DataAccessException{  
  90.         byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {  
  91.             @Override  
  92.             public byte[] doInRedis(RedisConnection connection) throws DataAccessException {  
  93.                 return connection.get(key);  
  94.             }  
  95.         });  
  96.         if (result == null) {  
  97.             return null;  
  98.         }  
  99.         return SerializerUtil.deserialize(result);  
  100.     }  
  101.   
  102.     /** 
  103.      * 删除指定key数据 
  104.      * @param key 
  105.      * @return 返回操作影响记录数 
  106.      */  
  107.     public Long del(final byte[] key){  
  108.         if (key.length == 0) {  
  109.             return 0l;  
  110.         }  
  111.         Long delNum = redisTemplate.execute(new RedisCallback<Long>() {  
  112.             @Override  
  113.             public Long doInRedis(RedisConnection connection) throws DataAccessException {  
  114.                 byte[] keys = key;  
  115.                 return connection.del(keys);  
  116.             }  
  117.         });  
  118.         return delNum;  
  119.     }  
  120.   
  121.     public Set<byte[]> keys(final String key){  
  122.         if (StringUtils.isEmpty(key)) {  
  123.             return null;  
  124.         }  
  125.         Set<byte[]> bytesSet = redisTemplate.execute(new RedisCallback<Set<byte[]>>() {  
  126.             @Override  
  127.             public Set<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {  
  128.                 byte[] keys = key.getBytes();  
  129.                 return connection.keys(keys);  
  130.             }  
  131.         });  
  132.   
  133.         return bytesSet;  
  134.     }  
  135.   
  136.     /** 
  137.      * dbSize 
  138.      */  
  139.     public Long dbSize(){  
  140.         Long delNum = redisTemplate.execute(new RedisCallback<Long>() {  
  141.             @Override  
  142.             public Long doInRedis(RedisConnection connection) throws DataAccessException {  
  143.                 return connection.dbSize();  
  144.             }  
  145.         });  
  146.         return delNum;  
  147.     }  
  148.   
  149.     /** 
  150.      * flushDB 
  151.      */  
  152.     public void flushDB() throws DataAccessException{  
  153.         redisTemplate.execute(new RedisCallback<Void>() {  
  154.             @Override  
  155.             public Void doInRedis(RedisConnection connection) throws DataAccessException {  
  156.                 connection.flushDb();  
  157.                 return null;  
  158.             }  
  159.         });  
  160.     }}  



7.  RedisCacheManager.java


[java]  view plain  copy
  1. import org.apache.shiro.cache.Cache;  
  2. import org.apache.shiro.cache.CacheException;  
  3. import org.apache.shiro.cache.CacheManager;  
  4. import org.slf4j.Logger;  
  5. import org.slf4j.LoggerFactory;  
  6.   
  7. import java.util.concurrent.ConcurrentHashMap;  
  8. import java.util.concurrent.ConcurrentMap;  
  9.   
  10. /** 
  11.  * @Author: 
  12.  * @Date: 2018-03-13 14:08 
  13.  * @Modified By: 
  14.  * @Description: 
  15.  */  
  16. public class RedisCacheManager implements CacheManager{  
  17.   
  18.     private static final Logger logger = LoggerFactory  
  19.             .getLogger(RedisCacheManager.class);  
  20.   
  21.     private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();  
  22.   
  23.     private RedisManager redisManager;  
  24.   
  25.     /** 
  26.      * The Redis key prefix for caches 
  27.      */  
  28.     private String keyPrefix = "shiro_redis_cache:";  
  29.   
  30.     /** 
  31.      * Returns the Redis session keys 
  32.      * prefix. 
  33.      * @return The prefix 
  34.      */  
  35.     public String getKeyPrefix() {  
  36.         return keyPrefix;  
  37.     }  
  38.   
  39.     /** 
  40.      * Sets the Redis sessions key 
  41.      * prefix. 
  42.      * @param keyPrefix The prefix 
  43.      */  
  44.     public void setKeyPrefix(String keyPrefix) {  
  45.         this.keyPrefix = keyPrefix;  
  46.     }  
  47.   
  48.     @Override  
  49.     public <K, V> Cache<K, V> getCache(String name) throws CacheException {  
  50.         logger.debug("获取名称为: " + name + " 的RedisCache实例");  
  51.   
  52.         Cache c = caches.get(name);  
  53.   
  54.         if (c == null) {  
  55.   
  56.             // initialize the Redis manager instance  
  57.             redisManager.init();  
  58.   
  59.             // create a new cache instance  
  60.             c = new RedisCache<K, V>(redisManager, keyPrefix);  
  61.   
  62.             // add it to the cache collection  
  63.             caches.put(name, c);  
  64.         }  
  65.         return c;  
  66.     }  
  67.   
  68.     public RedisManager getRedisManager() {  
  69.         return redisManager;  
  70.     }  
  71.   
  72.     public void setRedisManager(RedisManager redisManager) {  
  73.         this.redisManager = redisManager;  
  74.     }  
  75.   
  76. }  



8.  RedisCache.java


[java]  view plain  copy
  1. import org.apache.shiro.cache.Cache;  
  2. import org.apache.shiro.cache.CacheException;  
  3. import org.apache.shiro.util.CollectionUtils;  
  4. import org.slf4j.Logger;  
  5. import org.slf4j.LoggerFactory;  
  6.   
  7. import java.util.*;  
  8.   
  9. /** 
  10.  * @Author: 
  11.  * @Date: 2018-03-13 14:10 
  12.  * @Modified By: 
  13.  * @Description: 
  14.  */  
  15. public class RedisCache<K,V> implements Cache<K,V> {  
  16.     private Logger logger = LoggerFactory.getLogger(this.getClass());  
  17.   
  18.     /** 
  19.      * The wrapped Jedis instance. 
  20.      */  
  21.     private RedisManager cache;  
  22.   
  23.     /** 
  24.      * The Redis key prefix for the sessions 
  25.      */  
  26.     private String keyPrefix = "shiro_redis_session:";  
  27.   
  28.     /** 
  29.      * Returns the Redis session keys 
  30.      * prefix. 
  31.      * @return The prefix 
  32.      */  
  33.     public String getKeyPrefix() {  
  34.         return keyPrefix;  
  35.     }  
  36.   
  37.     /** 
  38.      * Sets the Redis sessions key 
  39.      * prefix. 
  40.      * @param keyPrefix The prefix 
  41.      */  
  42.     public void setKeyPrefix(String keyPrefix) {  
  43.         this.keyPrefix = keyPrefix;  
  44.     }  
  45.   
  46.     /** 
  47.      * 通过一个JedisManager实例构造RedisCache 
  48.      */  
  49.     public RedisCache(RedisManager cache){  
  50.         if (cache == null) {  
  51.             throw new IllegalArgumentException("Cache argument cannot be null.");  
  52.         }  
  53.         this.cache = cache;  
  54.     }  
  55.   
  56.     /** 
  57.      * Constructs a cache instance with the specified 
  58.      * Redis manager and using a custom key prefix. 
  59.      * @param cache The cache manager instance 
  60.      * @param prefix The Redis key prefix 
  61.      */  
  62.     public RedisCache(RedisManager cache,  
  63.                       String prefix){  
  64.   
  65.         this( cache );  
  66.   
  67.         this.keyPrefix = prefix;  
  68.     }  
  69.   
  70.     /** 
  71.      * 获得byte[]型的key 
  72.      * @param key 
  73.      * @return 
  74.      */  
  75.     private byte[] getByteKey(K key){  
  76.         if(key instanceof String){  
  77.             String preKey = this.keyPrefix + key;  
  78.             return preKey.getBytes();  
  79.         }else{  
  80.             return SerializerUtil.serialize(key);  
  81.         }  
  82.     }  
  83.   
  84.     @Override  
  85.     public V get(K key) throws CacheException {  
  86.         logger.debug("根据key从Redis中获取对象 key [" + key + "]");  
  87.         try {  
  88.             if (key == null) {  
  89.                 return null;  
  90.             }else{  
  91.                 byte[] rawValue = cache.get(getByteKey(key));  
  92.                 @SuppressWarnings("unchecked")  
  93.                 V value = (V) SerializerUtil.deserialize(rawValue);  
  94.                 return value;  
  95.             }  
  96.         } catch (Throwable t) {  
  97.             throw new CacheException(t);  
  98.         }  
  99.   
  100.     }  
  101.   
  102.     @Override  
  103.     public V put(K key, V value) throws CacheException {  
  104.         logger.debug("根据key从存储 key [" + key + "]");  
  105.         try {  
  106.             cache.set(getByteKey(key), SerializerUtil.serialize(value));  
  107.             return value;  
  108.         } catch (Throwable t) {  
  109.             throw new CacheException(t);  
  110.         }  
  111.     }  
  112.   
  113.     @Override  
  114.     public V remove(K key) throws CacheException {  
  115.         logger.debug("从redis中删除 key [" + key + "]");  
  116.         try {  
  117.             V previous = get(key);  
  118.             cache.del(getByteKey(key));  
  119.             return previous;  
  120.         } catch (Throwable t) {  
  121.             throw new CacheException(t);  
  122.         }  
  123.     }  
  124.   
  125.     @Override  
  126.     public void clear() throws CacheException {  
  127.         logger.debug("从redis中删除所有元素");  
  128.         try {  
  129.             cache.flushDB();  
  130.         } catch (Throwable t) {  
  131.             throw new CacheException(t);  
  132.         }  
  133.     }  
  134.   
  135.     @Override  
  136.     public int size() {  
  137.         try {  
  138.             Long longSize = new Long(cache.dbSize());  
  139.             return longSize.intValue();  
  140.         } catch (Throwable t) {  
  141.             throw new CacheException(t);  
  142.         }  
  143.     }  
  144.   
  145.     @SuppressWarnings("unchecked")  
  146.     @Override  
  147.     public Set<K> keys() {  
  148.         try {  
  149.             Set<byte[]> keys = cache.keys(this.keyPrefix + "*");  
  150.             if (CollectionUtils.isEmpty(keys)) {  
  151.                 return Collections.emptySet();  
  152.             }else{  
  153.                 Set<K> newKeys = new HashSet<K>();  
  154.                 for(byte[] key:keys){  
  155.                     newKeys.add((K)key);  
  156.                 }  
  157.                 return newKeys;  
  158.             }  
  159.         } catch (Throwable t) {  
  160.             throw new CacheException(t);  
  161.         }  
  162.     }  
  163.   
  164.     @Override  
  165.     public Collection<V> values() {  
  166.         try {  
  167.             Set<byte[]> keys = cache.keys(this.keyPrefix + "*");  
  168.             if (!CollectionUtils.isEmpty(keys)) {  
  169.                 List<V> values = new ArrayList<V>(keys.size());  
  170.                 for (byte[] key : keys) {  
  171.                     @SuppressWarnings("unchecked")  
  172.                     V value = get((K)key);  
  173.                     if (value != null) {  
  174.                         values.add(value);  
  175.                     }  
  176.                 }  
  177.                 return Collections.unmodifiableList(values);  
  178.             } else {  
  179.                 return Collections.emptyList();  
  180.             }  
  181.         } catch (Throwable t) {  
  182.             throw new CacheException(t);  
  183.         }  
  184.     }  
  185. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在基于Spring Boot的分布式架构中,可以采用以下几种方式来解决分布式环境下的Session共享问题: 1. 使用Session复制:在传统的集群环境中,可以将Session对象复制到所有服务器节点上,使得每个节点都拥有完整的Session数据。这种方式可以通过在负载均衡器后面配置会话复制或使用专门的会话复制技术实现。 2. 使用Session持久化:将Session对象的数据存储到外部共享存储中,如数据库或缓存系统(如Redis)。所有服务器节点都可以从共享存储中读取和写入Session数据。这种方式需要确保共享存储的高可用性和性能。 3. 使用无状态Session:将Session数据从服务器端移至客户端,在每个请求中包含所有必要的会话信息,如使用JWT(JSON Web Token)或类似的机制。这样服务器端就无需存储会话信息,从而实现无状态的分布式架构。 4. 使用分布式缓存:利用分布式缓存系统(如Redis)来存储Session数据,并通过在请求中传递唯一标识符(如Session ID)来进行访问。每个服务器节点都可以从分布式缓存中读取和写入Session数据。 5. 使用第三方解决方案:还可以使用一些第三方解决方案来处理分布式环境下的Session共享问题,如Spring SessionApache Shiro、Hazelcast等。 选择合适的解决方案取决于具体的业务需求和系统架构,并需要综合考虑性能、可伸缩性、复杂性和一致性等因素。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值