1. 程式人生 > >spring+shiro多節點session共享

spring+shiro多節點session共享

shiro我就不多介紹了,我的方案是重寫 shiro的sessionDAO,把session儲存到redis上,直接上程式碼

一、spring中配置

 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
       <!--  <property name="cacheManager" ref="shiroEhcacheManager"/> -->
        <property name="sessionManager" ref="sessionManager"></property>  
        <property name="realm" ref="shiroDbRealm"/>
       <!--  <property name="sessionMode" value="http"/> -->
 </bean>
首先是securityManager,由於是web專案,使用的是shiro自帶的DefaultWebSecurityManager,這裡沒有必要注入cacheManager,通過檢視原始碼可知,在這裡配的cacheManager最終會被set到sessionDAO中,由於我們要自己寫sessionDAO,所以沒必要,很多人沒有看原始碼,以為在這兒配了就能用,其實不然,要使得cacheManager生效,你接下來配置的sessionManager和sessionDAO都必須實現CacheManagerAware接口才行,sessionMode這個屬性,已經被shiro廢棄,後續shiro版本可能就沒了,這裡的sessionMode屬性影響是很大的,配置不同會影響sessionManager是否被重置,我們要配自己的sessionDAO,所有絕對是不用配該屬性的

接下來是sessionManager了

<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 
    	<!-- 設定全域性會話超時時間,預設30分鐘(1800000) -->  
        <property name="globalSessionTimeout" value="7200000" />  
        <!-- session儲存的實現 -->  
        <property name="sessionDAO" ref="redisSessionDAO" />
        <property name="sessionIdCookie.name" value="JSID"/>
</bean>
sessionManager使用shiro的DefaultWebSessionManager,設定了session的超時時間,配置自己寫的session,重點要說的時這個sessionIdCookie.name,shiro預設是通過cookie儲存的sessionId,cookie的key預設為JSESSIONID,例如:JSESSIONID=5575866c-96e5-4c34-9b3c-ebe2c07fd423,而tomcat或者其他的一些用到的框架可能會重寫這個鍵值對,因為JSESSIONID這個名字實在是太通用了,一旦被複寫,shiro自然就找不到sessionid對應的session了,這會導致一連串的問題,比如用著用著跳到登入頁面,獲取session中存好的引數獲取不到等,為了避免這個問題,配置了cookie的name

sessionDAO配置及redisManager配置

<bean id="redisSessionDAO" class="com.xxx.shiro.RedisSessionDAO">
     <property name="redisManager" ref="redisManager" />
</bean>
 <bean id="redisManager" class="com.xxx.shiro.RedisManager">
     <property name="host" value="${redis.hostname}"/>
     <property name="port" value="${redis.port}"/>
     <property name="expire" value="7200"/>
	    <!-- optional properties:
	    <property name="timeout" value="10000"/>
	    <property name="password" value="123456"/>
	    -->
</bean>
redisManager主要用來訪問redis的,當然也可以用spring提供的redis的template,我反正是沒用成功,有興趣的朋友試下

其他shiro配置

<bean id="shiroDbRealm" class="com.xxx.shiro.ShiroDBRealm"></bean>
    
<bean id="tokenFilter" class="com.xxx.shiro.TokenFilter"></bean>
    <!-- Shiro Filter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login"/>
        <property name="successUrl" value="/home"/>
        <property name="unauthorizedUrl" value="/home"/>
        <property name="filters">
			<map>
				<entry key="tkf" value-ref="tokenFilter"/>
			</map>
		</property>
        <property name="filterChainDefinitions">
            <value>
                /login = anon
                /captcha.png = anon
                /toLogin = anon
                /logout = logout
                /static/** = anon
                /weixin/** = anon
                /cxf/** = anon
                /api/oauth2/**=anon
		/api/** = anon ,tkf
                /** = authc
            </value>
        </property>
    </bean>

    <!-- 使用者授權資訊Cache, 採用EhCache -->
    <!-- <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml"/>
    </bean> -->

    <!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

二、java程式碼

public class RedisSessionDAO extends AbstractSessionDAO {

	private static Logger logger = LoggerFactory.getLogger(RedisSessionDAO.class);
	
	private RedisManager redisManager;
	
	/**
	 * The Redis key prefix for the sessions 
	 */
	private String keyPrefix = "shiro_redis_session:";
	
	@Override
	public void update(Session session) throws UnknownSessionException {
		this.saveSession(session);
	}
	
	/**
	 * save session
	 * @param session
	 * @throws UnknownSessionException
	 */
	private void saveSession(Session session) throws UnknownSessionException{
		if(session == null || session.getId() == null){
			logger.error("session or session id is null");
			return;
		}
		
		byte[] key = getByteKey(session.getId());
		byte[] value = SerializeUtils.serialize(session);
		session.setTimeout(redisManager.getExpire()*1000);		
		this.redisManager.set(key, value, redisManager.getExpire());
	}

	@Override
	public void delete(Session session) {
		if(session == null || session.getId() == null){
			logger.error("session or session id is null");
			return;
		}
		redisManager.del(this.getByteKey(session.getId()));

	}

	@Override
	public Collection<Session> getActiveSessions() {
		Set<Session> sessions = new HashSet<Session>();
		
		Set<byte[]> keys = redisManager.keys(this.keyPrefix + "*");
		if(keys != null && keys.size()>0){
			for(byte[] key:keys){
				Session s = (Session)SerializeUtils.deserialize(redisManager.get(key));
				sessions.add(s);
			}
		}
		
		return sessions;
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = this.generateSessionId(session);  
        this.assignSessionId(session, sessionId);
        this.saveSession(session);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		if(sessionId == null){
			logger.error("session id is null");
			return null;
		}
		Session s = (Session)SerializeUtils.deserialize(redisManager.get(this.getByteKey(sessionId)));
		return s;
	}
	
	/**
	 * 獲得byte[]型的key
	 * @param key
	 * @return
	 */
	private byte[] getByteKey(Serializable sessionId){
		String preKey = this.keyPrefix + sessionId;
		return preKey.getBytes();
	}

	public RedisManager getRedisManager() {
		return redisManager;
	}

	public void setRedisManager(RedisManager redisManager) {
		this.redisManager = redisManager;
		
		/**
		 * 初始化redisManager
		 */
		this.redisManager.init();
	}

	/**
	 * Returns the Redis session keys
	 * prefix.
	 * @return The prefix
	 */
	public String getKeyPrefix() {
		return keyPrefix;
	}

	/**
	 * Sets the Redis sessions key 
	 * prefix.
	 * @param keyPrefix The prefix
	 */
	public void setKeyPrefix(String keyPrefix) {
		this.keyPrefix = keyPrefix;
	}
	
	
}
在儲存session時,每次都重新設定了session的過期時間,按理說應該不需要,為了保險吧
public class RedisManager {
	
	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 RedisManager(){
		
	}
	
	/**
	 * 初始化方法
	 */
	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);該方法會導致高併發訪問時,報[B cannot be cast to java.lang.Long]異常
                     jedis.close();

		}
		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{
			jedis.close();

		}
		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{
			jedis.close();

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

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

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

		}
		return dbSize;
	}

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

		}
		return keys;
	}
	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getExpire() {
		return expire;
	}

	public void setExpire(int expire) {
		this.expire = expire;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	
	
}
序列化用的util類
public class SerializeUtils {
	
	private static Logger logger = LoggerFactory.getLogger(SerializeUtils.class);
	
	/**
	 * 反序列化
	 * @param bytes
	 * @return
	 */
	public static Object deserialize(byte[] bytes) {
		
		Object result = null;
		
		if (isEmpty(bytes)) {
			return null;
		}

		try {
			ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
			try {
				ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
				try {
					result = objectInputStream.readObject();
				}
				catch (ClassNotFoundException ex) {
					throw new Exception("Failed to deserialize object type", ex);
				}
			}
			catch (Throwable ex) {
				throw new Exception("Failed to deserialize", ex);
			}
		} catch (Exception e) {
			logger.error("Failed to deserialize",e);
		}
		return result;
	}
	
	public static boolean isEmpty(byte[] data) {
		return (data == null || data.length == 0);
	}

	/**
	 * 序列化
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		
		byte[] result = null;
		
		if (object == null) {
			return new byte[0];
		}
		try {
			ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
			try  {
				if (!(object instanceof Serializable)) {
					throw new IllegalArgumentException(SerializeUtils.class.getSimpleName() + " requires a Serializable payload " +
							"but received an object of type [" + object.getClass().getName() + "]");
				}
				ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
				objectOutputStream.writeObject(object);
				objectOutputStream.flush();
				result =  byteStream.toByteArray();
			}
			catch (Throwable ex) {
				throw new Exception("Failed to serialize", ex);
			}
		} catch (Exception ex) {
			logger.error("Failed to serialize",ex);
		}
		return result;
	}
}