shiro缓存

搭建好shiro的demo后,发现每一次验证权限都要调用自定义realm的doGetAuthorizationInfo方法,在方法里,从数据库读取用户的相关信息,为用户设置roles和Permission权限,如果每次都从数据库查询肯定是不行的,shiro框架默认使用ehcache缓存。配置方法如下

1. 引入shiro-encache包

2. 配置文件中注入bean

<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
	<property name="cacheManagerConfigFile" value="classpath:config/ehcache-shiro.xml" />
</bean>
其中,encache-shiro.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">

	<diskStore path="java.io.tmpdir" />

	<defaultCache maxElementsInMemory="2000" eternal="true"
		timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />


	<cache name="passwordRetryCache" maxElementsInMemory="2000"
		eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="0"
		overflowToDisk="false">
	</cache>

	<cache name="authorizationCache" maxElementsInMemory="2000"
		eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="0"
		overflowToDisk="false">
	</cache>

	<cache name="authenticationCache" maxElementsInMemory="2000"
		eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="0"
		overflowToDisk="false">
	</cache>

	<cache name="shiro-activeSessionCache" maxElementsInMemory="2000"
		eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="0"
		overflowToDisk="false">
	</cache>
</ehcache>
3. shiro的   中注入缓存对象

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	<property name="realm" ref="myrealm" />
	<property name="cacheManager" ref="cacheManager" />
</bean>

完成后,再次测试,发现多次验证权限时,doGetAuthorizationInfo方法只执行一次,说明缓存设置成功。


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值