本篇文章为大家展示了如何使用Shiro性能优化EhCache,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
* evict : 驱逐,赶出
ps : 使用shiro进行权限管理后,每次都需要调用realm查询角色和权限,每次都需要查数据库,性能不是很好
pps : 是否可以将数据库中的数据放到缓存中,减少数据库交互,提高性能?
一:技术选型
为什么使用ehcache而不使用redis缓存?
Shiro 默认对 ehcache 的支持

在后台管理系统中 ehcache 使用非常普遍
二:spring整合ehcache
(一)maven依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.8.RELEASE</version>
</dependency>
(二)导入ehcache.xml配置文件

<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="myCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
(三)将EhCache交给Spring管理

<!-- spring整合ehcache -->
<bean id="ehCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
三:shiro整合ehcache
(一)配置shiro的缓存管理器,封装ehcache

<!-- shiro封装ehCacheManager -->
<bean id="shiroCacheManager"
class="org.apache.shiro.cache.ehcache.EhCacheManager" >
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
(二)将shiro的缓存管理器,注入到安全管理器中
<!-- 配置subject的后台推手securityManager -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
<property name="cacheManager" ref="shiroCacheManager"/>
</bean>
(三)为认证授权数据指定缓存区
<bean id="myRealm" class="club.info.bos.realm.MyRealm">
<property name="authorizationCacheName" value="myCache"/>
</bean>
四:缓存声明
spring提供一套整合缓存器的注解 
开启注解缓存
<bean id="springCacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
<cache:annotation-driven cache-manager="springCacheManager"/>
(一)@CacheEvict
清除缓存,通常数据库数据发生变化后,清除缓存,如增,删改
@Override
@CacheEvict(value="myCache",allEntries=true)
public void save(User user) {
userDao.save(user);
}
(二)@Cacheable("缓存区名称")
1.缓存无参方法的返回值
@Override
@Cacheable("myCache")
public List<User> findAll() {
return userDao.findAll();
}
2.缓存有参方法的返回值

@Override
@Cacheable(value="myCache",key="#pageable.pageNumber+'_'+#pageable.pageSize")
public List<User> findPageData(Pageable pageable) {
return userDao.findAll(pageable);
}
上述内容就是如何使用Shiro性能优化EhCache,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注天达云行业资讯频道。