1、背景
當咱們使用了nginx作項目集羣之後,就會出現一個很嚴重的問題亟待解決,那就是:tomcat集羣之間如何實現session共享的問題,若是這個問題不解決,就會出現登錄事後再次請求資源依舊須要登錄的問題。這篇文章咱們就解決這個問題。html
2、實現步驟
說明:本篇是在spring+shiro集成的基礎上進行改進的,若是不知道spring和shiro怎麼集成,請移步:spring集成shiro作登錄認證java
1.在pom.xml中添加shiro-redis和jedis的依賴nginx
<dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis</artifactId> <version>2.4.2.1-RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.2</version> </dependency>
2.首先咱們須要對redis進行集成,在resources下新建config.propertiesgit
#redis pool config redis.pool.maxActive=200 redis.pool.maxIdle=100 redis.pool.maxWait=100 redis.pool.testOnBorrow=true #redis config redis.host=192.168.85.129 redis.port=6379 redis.timeout=2000 redis.password=123456 redis.dbindex=8 redis.default.expire=1800000
3.在resources/spring文件夾下新建spring-redis.xml來集成redis操做客戶端github
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <description>Redis configuration</description> <bean id="redisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="${redis.pool.maxActive}"/> <property name="maxIdle" value="${redis.pool.maxIdle}"/> <property name="maxWaitMillis" value="${redis.pool.maxWait}"/> <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/> </bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy"> <constructor-arg ref="redisPoolConfig"/> <constructor-arg value="${redis.host}"/> <constructor-arg type="int" value="${redis.port}"/> <constructor-arg type="int" value="${redis.timeout}"/> <constructor-arg type="java.lang.String" value="${redis.password}"/> <constructor-arg type="int" value="${redis.dbindex}"/> </bean> <bean id="redisClient" class="com.hafiz.www.redis.RedisClient"> <constructor-arg name="jedisPool" ref="jedisPool"/> <property name="expire" value="${redis.default.expire}"/> </bean> </beans>
4.添加redisClient.java做爲訪問redis的客戶端web
package com.hafiz.www.redis; import org.crazycake.shiro.RedisManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Set; /** * Desc: Jedis 操做客戶端 * Created by hafiz.zhang on 2017/7/21. */ public class RedisClient extends RedisManager{ private static final Logger LOGGER = LoggerFactory.getLogger(RedisClient.class); private static JedisPool jedisPool = null; public RedisClient(JedisPool jedisPool) { this.jedisPool = jedisPool; } public void init() { super.init(); } @Override public byte[] get(byte[] key) { Jedis jedis = jedisPool.getResource(); byte[] value; try { value = jedis.get(key); } catch (Exception e) { LOGGER.error("redis key:{} get value occur exception", new String(key)); throw new RuntimeException("redis operation error:", e); } finally { jedis.close(); } return value; } @Override public byte[] set(byte[] key, byte[] value) { Jedis jedis = jedisPool.getResource(); try { jedis.set(key, value); Integer expire = getExpire(); if(expire != 0) { jedis.expire(key, expire); } } catch (Exception e) { LOGGER.error("redis key:{} set value:{} occur exception", new String(key), new String(value)); throw new RuntimeException("redis operation error:", e); } finally { jedis.close(); } return value; } @Override 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); } } catch (Exception e) { LOGGER.error("redis key:{} set value:{} in expire:{} occur exception", new String(key), new String(value), expire); throw new RuntimeException("redis operation error:", e); } finally { jedis.close(); } return value; } @Override public void del(byte[] key) { Jedis jedis = jedisPool.getResource(); try { jedis.del(key); } catch (Exception e) { LOGGER.error("redis key:{} del value occur exception", new String(key)); throw new RuntimeException("redis operation error:", e); } finally { jedis.close(); } } @Override public void flushDB() { Jedis jedis = jedisPool.getResource(); try { jedis.flushDB(); } catch (Exception e) { LOGGER.error("redis flushDB occur exception"); throw new RuntimeException("redis operation error:", e); } finally { jedis.close(); } } @Override public Long dbSize() { Long dbSize = Long.valueOf(0L); Jedis jedis = jedisPool.getResource(); try { dbSize = jedis.dbSize(); } catch (Exception e) { LOGGER.error("redis get dbSize occur exception"); throw new RuntimeException("redis operation error:", e); } finally { jedis.close(); } return dbSize; } @Override public Set<byte[]> keys(String pattern) { Set keys = null; Jedis jedis = jedisPool.getResource(); try { keys = jedis.keys(pattern.getBytes()); } catch (Exception e) { LOGGER.error("redis get keys in pattern:{} occur exception", pattern); throw new RuntimeException("redis operation error:", e); } finally { jedis.close(); } return keys; } }
5.接着,咱們對spring-shiro.xml作以下修改(紅色標記的部分)redis
<?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:util="http://www.springframework.org/schema/util" 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"> <description>Shiro Configuration</description> <!--shiro-redis redisCacheManager--> <bean id="redisCacheManager" class="org.crazycake.shiro.RedisCacheManager"> <property name="keyPrefix" value="shiro_redis_session:"/> <property name="redisManager" ref="redisClient"/> </bean> <!--custom myself realm--> <bean id="customRealm" class="com.hafiz.www.shiro.CustomRealm"> <property name="cacheManager" ref="redisCacheManager"/> </bean> <!--redisSessionDAO--> <bean id="redisSessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO"></bean> <!--simpleCookie,不定義在集羣環境下會出現There is no session with id ....--> <bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> <constructor-arg name="name" value="custom.session"/> <property name="path" value="/"/> </bean> <!--sessionManager--> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="sessionDAO" ref="redisSessionDAO"/> <property name="sessionIdCookie" ref="simpleCookie"/> </bean> <!--Shiro`s main business-tier object for web-enable applications--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="customRealm"/> <property name="cacheManager" ref="redisCacheManager"/> <property name="sessionManager" ref="sessionManager"/> </bean> <!--shiro filter--> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/login.html"/> <property name="successUrl" value="/index.html"/> <property name="unauthorizedUrl" value="/unauthorized.html"/> <property name="filters"> <util:map> <entry key="auth"> <bean class="com.hafiz.www.filter.AuthorizeFilter"/> </entry> </util:map> </property> <property name="filterChainDefinitions"> <value> /login.json = anon /logout.json = anon /js/** = anon / = authc /** = auth </value> </property> </bean> </beans>
6.spring.xml作以下修改spring
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:config.properties,classpath:jdbc.properties"/> <import resource="spring-*.xml"/> </beans>
到此咱們就完了shiro+redis實現session共享的問題,其實也很簡單,其中的實現邏輯也很簡單,就是shiro的攔截器會首先去redis裏面獲取session,做爲當本次請求的session.apache
其餘代碼以及簡單測試代碼再也不貼出,給出github地址:https://github.com/hafizzhang/shiro-session-cluster.gitjson
3、總結
經過本文,咱們就完成了spring+shiro+redis實現集羣session共享的問題,通過親測可行。但有一點遺憾的地方,就是每次請求至少會有8次redis的讀操做,一次寫操做,這個問題尚未找到很好的解決辦法,本地使用ehcahe也不太現實,由於涉及到本地緩存和redis緩存同步的問題,若是你有好的辦法,歡迎討論交流學習!