在pom.xml中注入緩存依賴,版本(Sep 09, 2016)spring-context-support
包含支持UI模版(Velocity,FreeMarker,JasperReports),
郵件服務,
腳本服務(JRuby),
緩存Cache(EHCache),
任務計劃Scheduling(uartz)。
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.3.2</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>4.3.7.RELEASE</version>
</dependency>
在ShiroConfiguration中注入緩存
/*** shiro緩存管理器;* 需要注入對應的其它的實體類中:* 1、安全管理器:securityManager* 可見securityManager是整個shiro的核心;* @return*/@Beanpublic EhCacheManager ehCacheManager(){System.out.println("ShiroConfiguration.getEhCacheManager()");EhCacheManager cacheManager = new EhCacheManager();cacheManager.setCacheManagerConfigFile("classpath:config/ehcache-shiro.xml");return cacheManager;}
將緩存對象注入到SecurityManager中:
@Beanpublic SecurityManager securityManager(){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(myShiroRealm());securityManager.setCacheManager(ehCacheManager());return securityManager;}
添加緩存配置文件:
在src/main/resouces/config添加ehcache-shiro.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="es"><diskStore path="java.io.tmpdir"/><!--name:緩存名稱。maxElementsInMemory:緩存最大數目maxElementsOnDisk:硬盤最大緩存個數。eternal:對象是否永久有效,一但設置了,timeout將不起作用。overflowToDisk:是否保存到磁盤,當系統當機時timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介于創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。clearOnFlush:內存數量最大時是否清除。memoryStoreEvictionPolicy:Ehcache的三種清空策略;FIFO,first in first out,這個是大家最熟的,先進先出。LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那么現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。--><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="false"diskPersistent="false"diskExpiryThreadIntervalSeconds="120"/><!-- 登錄記錄緩存鎖定10分鐘 --><cache name="passwordRetryCache"maxEntriesLocalHeap="2000"eternal="false"timeToIdleSeconds="3600"timeToLiveSeconds="0"overflowToDisk="false"statistics="true"></cache></ehcache>
在配置文件上已經有很詳細的解釋了,所以這里就過多介紹ehcache的配置了。
運行程序訪問:http://127.0.0.1:8080/userInfo/userAdd
查看控制臺的打印信息:
權限配置-->MyShiroRealm.doGetAuthorizationInfo()
這個信息就只打印一次了,說明我們的緩存生效了。
文章主要參考于作者林祥纖的博客
http://412887952-qq-com.iteye.com/blog/2299780