1. 程式人生 > >010-shiro與spring web項目整合【四】緩存Ehcache、Redis

010-shiro與spring web項目整合【四】緩存Ehcache、Redis

principal eba view event ica inter element edi value

一、Ehcache

shiro每次授權都會通過realm獲取權限信息,為了提高訪問速度需要添加緩存,第一次從realm中讀取權限數據,之後不再讀取,這裏Shiro和Ehcache整合。

1、添加Ehcache的jar包

技術分享
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.5.3</
version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.3.2</version> </dependency>
View Code

2、配置cacheManager

在applicationContext-shiro.xml中配置緩存管理器。

    <!-- securityManager安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="customRealm"/>
        <!-- 註入緩存管理器 -->
        <property name="cacheManager" ref="cacheManager"/>
        <!--
註入session管理器 --> <property name="sessionManager" ref="sessionManager"/> <!-- 記住我 --> <property name="rememberMeManager" ref="rememberMeManager"/> </bean> <!-- 緩存管理器 --> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/> </bean>

3、配置shiro-ehcache.xml

技術分享
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!--diskStore:緩存數據持久化的目錄 地址  -->
    <diskStore path="F:\develop\ehcache" />
    <defaultCache 
        maxElementsInMemory="1000" 
        maxElementsOnDisk="10000000"
        eternal="false" 
        overflowToDisk="false" 
        diskPersistent="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120" 
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>
View Code

4、清空緩存

  當用戶權限修改後,用戶再次登陸shiro會自動調用realm從數據庫獲取權限數據,如果在修改權限後想立即清除緩存則可以調用realm的clearCache方法清除緩存。

  realm中定義clearCached方法:

    //清除緩存
    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }

  在權限修改後調用realm中的方法,realm已經由spring管理,所以從spring中獲取realm實例,調用clearCached方法。

010-shiro與spring web項目整合【四】緩存Ehcache、Redis