本篇文章为大家展示了如何使用Shiro性能优化EhCache,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
* evict : 驱逐,赶出
ps : 使用shiro进行权限管理后,每次都需要调用realm查询角色和权限,每次都需要查数据库,性能不是很好
pps : 是否可以将数据库中的数据放到缓存中,减少数据库交互,提高性能?
Shiro 默认对 ehcache 的支持
在后台管理系统中 ehcache 使用非常普遍
<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-core.jar
包 ,将ehcache-failsafe.xml
复制src/main/resources
改名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>
<!-- spring整合ehcache -->
<bean id="ehCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
<!-- shiro封装ehCacheManager -->
<bean id="shiroCacheManager"
class="org.apache.shiro.cache.ehcache.EhCacheManager" >
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
<!-- 配置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>
注意 : 需要缓存的对象要实现serializable接口
spring提供一套整合缓存器的注解
开启注解缓存
<bean id="springCacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
<cache:annotation-driven cache-manager="springCacheManager"/>
清除缓存,通常数据库数据发生变化后,清除缓存,如增,删改
@Override
@CacheEvict(value="myCache",allEntries=true)
public void save(User user) {
userDao.save(user);
}
能缓存的,查询后缓存
@Override
@Cacheable("myCache")
public List<User> findAll() {
return userDao.findAll();
}
针对数据在不同条件下进行不同缓存,我们可以指定缓存的key
,支持对象嵌套,支持spel表达式
@Override
@Cacheable(value="myCache",key="#pageable.pageNumber+'_'+#pageable.pageSize")
public List<User> findPageData(Pageable pageable) {
return userDao.findAll(pageable);
}
上述内容就是如何使用Shiro性能优化EhCache,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4221889/blog/3124329