1.引入相关jar包
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.7.0</version>
</dependency>
2.在resources目录下创建cache/ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
name="project">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- external:缓存对象是否一直存在,如果设置为true的话,那么timeout就没有效果,缓存就会一直存在,一般默认就是false -->
<!-- maxElementsInMemory:内存中可以缓存多少个缓存条目 -->
<!-- overflowToDisk:如果内存不够的时候,是否溢出到磁盘 -->
<!-- diskPersistent:是否启用磁盘持久化的机制,在jvm崩溃的时候和重启之间 -->
<!-- timeToIdleSeconds:对象最大的闲置的时间,如果超出闲置的时间,可能就会过期 单位:秒 当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大-->
<!-- timeToLiveSeconds:对象最多存活的时间 单位:秒 当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是存活时间无穷大-->
<!-- memoryStoreEvictionPolicy:当缓存数量达到了最大的指定条目数的时候,需要采用一定的算法,从缓存中清除一批数据,LRU,最近最少使用算法,最近一段时间内,最少使用的那些数据,就被干掉了 -->
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<Cache
memoryStoreEvictionPolicy="LRU"
name="bookList"
maxEntriesLocalHeap="10000"
timeToLiveSeconds="120"
eternal="false"
timeToIdleSeconds="120">
</Cache>
</ehcache>
我这里是要缓存图书列表,避免每次查询。
3.shiroConfig中编写
/**
* EhCache
*/
@Bean
public EhCacheManager ehCacheManager() {
//创建cacheManager对象
CacheManager cacheManager = CacheManager.getCacheManager("project");
//创建对象
EhCacheManager ehCacheManager = new EhCacheManager();
//获取配置文件流对象
InputStream is = null;
try {
is = ResourceUtils.getInputStreamForPath("classpath:cache/ehcache.xml");
} catch (IOException e) {
e.printStackTrace();
}
if (cacheManager == null) {
ehCacheManager.setCacheManager(new CacheManager(is));
} else {
ehCacheManager.setCacheManager(cacheManager);
}
return ehCacheManager;
}
4.编写测试Controller
@RequestMapping("/getCache")
@ResponseBody
public ResultUtils getMap() {
String[] cacheNames = cacheService.getCacheNames();
return ResultUtils.success("cacheNames",cacheNames);
}
查看结果:
这里有UserRealm的缓存,说明shiro管理ehcache成功,同时也有bookList