1. 程式人生 > >Apache shiro叢集實現 (六)分散式集群系統下的高可用session解決方案---Session共享

Apache shiro叢集實現 (六)分散式集群系統下的高可用session解決方案---Session共享


      Apache Shiro的基本配置和構成這裡就不詳細說明了,其官網有說明文件,這裡僅僅說明叢集的解決方案,詳細配置:shiro web config

    Apache Shiro叢集要解決2個問題,一個是session的共享問題,一個是授權資訊的cache共享問題,官網給的例子是Ehcache的實現,在配置說明上不算很詳細,我這裡用nosql(redis)替代了ehcache做了session和cache的儲存。

shiro spring的預設配置(單機,非叢集)

<span style="font-size:18px;"><span style="font-size:18px;"><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
    <property name="realm" ref="shiroDbRealm" />  
    <property name="cacheManager" ref="memoryConstrainedCacheManager" />  
</bean>  
  
<!-- 自定義Realm -->  
<bean id="shiroDbRealm" class="com.xxx.security.shiro.custom.ShiroDbRealm">  
    <property name="credentialsMatcher" ref="customCredentialsMather"></property>  
</bean>   
<!-- 使用者授權資訊Cache(本機記憶體實現) -->  
<bean id="memoryConstrainedCacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />    
  
<!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->  
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
  
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
    <property name="securityManager" ref="securityManager" />  
    <property name="loginUrl" value="/login" />  
    <property name="successUrl" value="/project" />  
    <property name="filterChainDefinitions">  
        <value>  
        /login = authc  
        /logout = logout              
    </value>  
    </property>  
</bean> </span></span>

上面的配置是shiro非叢集下的配置,DefaultWebSecurityManager類不需要注入sessionManager屬性,它會使用預設的sessionManager類,請看原始碼
<span style="font-size:18px;"><span style="font-size:18px;">    public DefaultWebSecurityManager() {  
            super();  
            ((DefaultSubjectDAO) this.subjectDAO).setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator());  
            this.sessionMode = HTTP_SESSION_MODE;  
            setSubjectFactory(new DefaultWebSubjectFactory());  
            setRememberMeManager(new CookieRememberMeManager());  
            setSessionManager(new ServletContainerSessionManager());  
    }  </span></span>

在最後一行,set了預設的servlet容器實現的sessionManager,sessionManager會管理session的建立、刪除等等。如果我們需要讓session在叢集中共享,就需要替換這個預設的sessionManager。在其官網上原話是這樣的:
<span style="font-size:18px;"><span style="font-size:18px;">    Native Sessions  
      
    If you want your session configuration settings and clustering to be portable across servlet containers  
    (e.g. Jetty in testing, but Tomcat or JBoss in production), or you want to control specific session/clustering   
    features, you can enable Shiro's native session management.  
      
    The word 'Native' here means that Shiro's own enterprise session management implementation will be used to support   
    all Subject and HttpServletRequest sessions and bypass the servlet container completely. But rest assured - Shiro   
    implements the relevant parts of the Servlet specification directly so any existing web/http related code works as   
    expected and never needs to 'know' that Shiro is transparently managing sessions.  
      
    DefaultWebSessionManager  
      
    To enable native session management for your web application, you will need to configure a native web-capable   
    session manager to override the default servlet container-based one. You can do that by configuring an instance of   
    DefaultWebSessionManager on Shiro's SecurityManager.   </span></span>

我們可以看到如果要用叢集,就需要用本地會話,這裡shiro給我準備了一個預設的native session manager,DefaultWebSessionManager,所以我們要修改spring配置檔案,注入DefaultWebSessionManager
<span style="font-size:18px;"><span style="font-size:18px;">    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="sessionManager" ref="defaultWebSessionManager" />  
        <property name="realm" ref="shiroDbRealm" />  
        <property name="cacheManager" ref="memoryConstrainedCacheManager" />  
    </bean>  
    <bean id="defaultWebSessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  
        <property name="globalSessionTimeout" value="1200000" />  
    </bean>  </span></span>
我們繼續看DefaultWebSessionManager的原始碼,發現其父類DefaultSessionManager中有sessionDAO屬性,這個屬性是真正實現了session儲存的類,這個就是我們自己實現的redis session的儲存類。
<span style="font-size:18px;"><span style="font-size:18px;">    protected SessionDAO sessionDAO;  
      
    private CacheManager cacheManager;  
      
    private boolean deleteInvalidSessions;  
      
    public DefaultSessionManager() {  
        this.deleteInvalidSessions = true;  
        this.sessionFactory = new SimpleSessionFactory();  
        this.sessionDAO = new MemorySessionDAO();  
    }  </span></span>

這裡我們看到了,如果不自己注入sessionDAO,defaultWebSessionManager會使用MemorySessionDAO做為預設實現類,這個肯定不是我們想要的,所以這就自己動手實現sessionDAO吧。
<span style="font-size:18px;"><span style="font-size:18px;">package com.tgb.itoo.authority.cache;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RedisSessionDAO extends AbstractSessionDAO {

	private static Logger logger = LoggerFactory.getLogger(RedisSessionDAO.class);
	/**
	 * shiro-redis的session物件字首
	 */
	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()));

	}

	//用來統計當前活動的session
	@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;
	}
}
</span></span>


我們自定義RedisSessionDAO繼承AbstractSessionDAO,實現對session操作的方法,可以用redis、mongoDB等進行實現。

這個是自己redis的RedisCacheManager儲存實現類:

<span style="font-size:18px;"><span style="font-size:18px;">package com.tgb.itoo.authority.cache;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RedisCacheManager implements CacheManager{

	private static final Logger logger = LoggerFactory
			.getLogger(RedisCacheManager.class);

	// fast lookup by name map
	private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();

	private RedisManager redisManager;

	/**
	 * The Redis key prefix for caches 
	 */
	private String keyPrefix = "shiro_redis_cache:";
	
	/**
	 * 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;
	}
	
	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		logger.debug("獲取名稱為: " + name + " 的RedisCache例項");
		
		Cache c = caches.get(name);
		
		if (c == null) {

			// initialize the Redis manager instance
			redisManager.init();
			
			// create a new cache instance
			c = new RedisCache<K, V>(redisManager, keyPrefix);
			
			// add it to the cache collection
			caches.put(name, c);
		}
		return c;
	}

	public RedisManager getRedisManager() {
		return redisManager;
	}

	public void setRedisManager(RedisManager redisManager) {
		this.redisManager = redisManager;
	}
}
</span></span>
這樣RedisSessionDAO我們就完成了,下面繼續修改我們spring配置檔案:
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
	http://www.springframework.org/schema/tx  
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	default-lazy-init="true">

	<!-- 註解支援 -->
	<context:annotation-config />
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:config/shiro-cas.properties</value>
			</list>
		</property>
	</bean>
	
	
	
	<jee:local-slsb id="PermissionManager"
		jndi-name="java:global/itoo-authority-role-ear/itoo-authority-shiro-core-0.0.1-SNAPSHOT/PermissionManager!com.tgb.itoo.authority.service.ShiroBean"
		business-interface="com.tgb.itoo.authority.service.ShiroBean"></jee:local-slsb>

<!-- 	<jee:jndi-lookup id="PermissionManager" -->

<!-- 	jndi-name="ejb:itoo-authority-shiro-ear/itoo-authority-shiro-core-0.0.1-SNAPSHOT/PermissionManager!com.tgb.itoo.authority.service.ShiroBean" -->

<!-- 	lookup-on-startup="true" cache="true" environment-ref="evn"> -->

<!-- 	</jee:jndi-lookup> -->
	<!-- shiro過濾器 start -->
	<bean id="shiroSecurityFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager"></property>
		<property name="loginUrl" value="${loginUrl}"></property>
		<property name="successUrl" value="${successUrl}"></property>
		<property name="filters">
			<map>
				<entry key="casFilter">
					<bean class="org.apache.shiro.cas.CasFilter">
						<!--配置驗證錯誤時的失敗頁面 /main 為系統登入頁面 -->
						<property name="failureUrl" value="/message.jsp" />
					</bean>
				</entry>
			</map>
		</property>
		<!-- 過濾器鏈,請求url對應的過濾器 -->
		<property name="filterChainDefinitions">
			<value>
				/message.jsp=anon
				/logout=logout
				/shiro-cas=casFilter
				/** =user
			</value>
		</property>
	</bean>
	<!-- shiro過濾器 end -->

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

	<!-- 第三:shiro管理中心類 start-李社河 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="shiroRealm"></property>
		<property name="sessionMode" value="http"></property>
		<property name="subjectFactory" ref="casSubjectFactory"></property>
		<!-- ehcahe快取shiro自帶 -->
		<!-- <property name="cacheManager" ref="shiroEhcacheManager"></property> -->

		<!-- redis快取 -->
		<property name="cacheManager" ref="redisCacheManager" />

		<!-- sessionManager -->
		<property name="sessionManager" ref="sessionManager"></property>
	</bean>


	<!-- 快取管理器redis-start-李社河-2015年4月14日 -->

	<!-- sessionManager -->
	<!-- <bean id="sessionManager" -->
	<!-- class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> -->
	<!-- <property name="sessionDAO" ref="redisSessionDAO" /> -->
	<!-- </bean> -->

	<!-- 自定義redisManager-redis -->
	<bean id="redisCacheManager" class="com.tgb.itoo.authority.cache.RedisCacheManager">
		<property name="redisManager" ref="redisManager" />
	</bean>
	<!-- 自定義cacheManager -->
	<bean id="redisCache" class="com.tgb.itoo.authority.cache.RedisCache">
		<constructor-arg ref="redisManager"></constructor-arg>
	</bean>

	<bean id="redisManager" class="com.tgb.itoo.authority.cache.RedisManager"></bean>

	<!-- 快取管理器redis-end-李社河-2015年4月14日 -->



	<!-- session會話儲存的實現類 -->
	<bean id="redisShiroSessionDAO" class="com.tgb.itoo.authority.cache.RedisSessionDAO">
		<property name="redisManager" ref="redisManager" />
	</bean>



	<!-- sessionManager -->
	<!-- session管理器 -->
	<bean id="sessionManager"
		class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
		<!-- 設定全域性會話超時時間,預設30分鐘(1800000) -->
		<property name="globalSessionTimeout" value="1800000" />
		<!-- 是否在會話過期後會呼叫SessionDAO的delete方法刪除會話 預設true -->
		<property name="deleteInvalidSessions" value="true" />

		<!-- 會話驗證器排程時間 -->
		<property name="sessionValidationInterval" value="1800000" />

		<!-- session儲存的實現 -->
		<property name="sessionDAO" ref="redisShiroSessionDAO" />
		<!-- sessionIdCookie的實現,用於重寫覆蓋容器預設的JSESSIONID -->
		<property name="sessionIdCookie" ref="sharesession" />
		<!-- 定時檢查失效的session -->
		<property name="sessionValidationSchedulerEnabled" value="true" />

	</bean>


	<!-- sessionIdCookie的實現,用於重寫覆蓋容器預設的JSESSIONID -->
	<bean id="sharesession" class="org.apache.shiro.web.servlet.SimpleCookie">
		<!-- cookie的name,對應的預設是 JSESSIONID -->
		<constructor-arg name="name" value="SHAREJSESSIONID" />
		<!-- jsessionId的path為 / 用於多個系統共享jsessionId -->
		<property name="path" value="/" />
		<property name="httpOnly" value="true"/>
	</bean>







	<!-- 第一:shiro於資料互動的類 ,自己寫的類的實現-ShiroRealmBean自己重寫的類的實現 -->
	<bean id="shiroRealm" class="com.tgb.itoo.authority.service.ShiroRealmBean">
		<property name="defaultRoles" value="user"></property>

		<!-- 注入自己實現的類,授權的過程-PermissionManager是雲平臺重寫的授權的過程,使用者Id->角色->資源->查詢許可權-李社河2015年4月15日 -->
		<property name="permissionMgr" ref="PermissionManager"></property>
		<property name="casServerUrlPrefix" value="${casServerUrlPrefix}"></property>
		<property name="casService" value="${casService}"></property>
	</bean>

	<bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory" />

	<!-- shiro的自帶快取管理器encahe -->
	<!-- <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> -->
	<!-- <property name="cacheManagerConfigFile" value="classpath:config/ehcache-shiro.xml" 
		/> -->
	<!-- </bean> -->

	<!-- 開啟shiro的註解,需藉助SpringAOP掃描使用Shiro註解的類,並在必要時進行安全邏輯驗證 -->
	<bean
		class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
		depends-on="lifecycleBeanPostProcessor"></bean>
	<bean
		class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>
</beans>
</span>

這樣第一個問題,session的共享問題我們就解決好了,下一篇介紹另一個問題,cache的共享問題。