04 shiro的缓存管理

前面我们看了shiro与spring的整合,接下来我们来了解一下shiro的缓存管理。

1、前提约束

2、理论解释

继承了AuthorizingRealm的类中有两个方法会被重写,一个是认证逻辑,一个是授权逻辑。认证逻辑用来约束账号密码是否正确,授权逻辑用来确认是否具有某些权限。授权逻辑会因为以下三种情况被触发:

  • java代码中subject.hasRole、subject.isPermitted等方法调用
  • java代码中@RequiresRoles、@RequiresPermissions等注解的使用
  • jsp页面中shiro:hasPermission、<shiro:hasRole等标签的使用
    这么多的逻辑都会触发授权方法的执行,如果在授权方法去查询数据库,那就意味着会非常频繁的访问数据库,缓存便应运而生。

3、操作步骤

  • 在applicationContext-shiro.xml中确保有以下几个标签
    <bean id="userRealm" class="net.wanho.security.MyRealm">
        <property name="authenticationCachingEnabled" value="true"></property>
        <property name="authorizationCachingEnabled" value="true"></property>
    </bean>
    <!--缓存管理-->
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/>

    <!--安全管理器-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm"/>
        <property name="cacheManager" ref="cacheManager"></property>
    </bean>

到这里,就可以看到缓存的效果了,用户不会每次都去查数据库;但要注意的一点是,一旦权限有所改变,务必要让缓存失效,让授权逻辑再去查询数据库,保证数据一致性。
以上就是shiro中的缓存管理。

posted @ 2020-03-18 20:57  张力的程序园  阅读(199)  评论(0)    收藏  举报