Shiro学习笔记(6)——shiro缓存

缓存

每一次给用户授权时,都是通过realm从数据库中查询权限,为了避免频繁的查询数据库,shiro给我们提供了缓存的能力

用户认证通过后:
第一次授权:通过realm从数据库中查询
第二次授权:直接从缓存中查询

引入包
1. shiro-ehcache.jar
2. ehcache-core.jar

配置缓存

创建缓存文件

在src下创建shiro-ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!--diskStore:缓存数据持久化的目录 地址  -->
    <diskStore path="F:\develop\ehcache" />
    <defaultCache 
        maxElementsInMemory="1000" 
        maxElementsOnDisk="10000000"
        eternal="false" 
        overflowToDisk="false" 
        diskPersistent="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120" 
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

配置缓存管理器

<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="userRealm" />
    <!-- 注入缓存管理器 -->
    <property name="cacheManager" ref="cacheManager"/>
</bean>
<!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
</bean>

清除缓存

一般情况下,用户正常退出和非正常退出(如关闭浏览器)都会自动清空缓存,但是有时候我们需要手动清空缓存。
例如:修改了一个用户的权限,需要手动清空缓存,否则这个用户只要不退出,权限就一直不改变。

手动情况缓存需要在realm中定义一个方法,然后在其他代码中调用它

在reaml中定义:

//清除缓存
    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }

在其他代码中调用:先注入reaml,在执行clearCached方法

@autowire 
private UserRealm userRealm;

userRealm.clearCached();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值