shiro-04shiro的缓存

来源:互联网 发布:亲爱的程序员txt百度云 编辑:程序博客网 时间:2024/05/13 11:23

注:
 有关shiro的内容介绍全部围绕springrain项目, 具体的springrain项目demo可以去之前的文章里面下载.

 因为是权限拦截校验,很多方法调用的频率是非常频繁的,为了更好的性能,shiro拥有一套完整的缓存体系,特别是针对web领域,做了部分增强.

 先看下缓存在shiro的权限管理器中的配置:

    <!-- 权限管理器 -->    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    <!-- 数据库认证的实现 org.springrain.frame.shiro.ShiroDbRealm -->    <property name="realm" ref="shiroDbRealm" />    <!-- session 管理器 -->    <property name="sessionManager" ref="sessionManager" />    <!-- 缓存管理器 -->    <property name="cacheManager" ref="shiroCacheManager" />    </bean>    <bean id="shiroCacheManager"  class="org.apache.shiro.cache.MemoryConstrainedCacheManager"   />

 cacheManager就是shiro的缓存管理器,springrain默认使用了shiro提供的MemoryConstrainedCacheManager,也可以实现相应的接口,实现自定义的cacheManager,例如springrain扩展的ShiroRedisCacheManager.
 缓存的用途主要是两个.一:权限相关的授权,要是每次都从数据库查询,太不合理了.二:对session对象的缓存,实现分布式的session共享.
 授权当然是有realm来做了,看下springrain中shiroDbRealm对缓存的支持.

    public ShiroDbRealm() {        // 认证缓存        // super.setAuthenticationCacheName(GlobalStatic.authenticationCacheName);        super.setAuthenticationCachingEnabled(false);        // 授权缓存        super.setAuthorizationCacheName(GlobalStatic.authorizationCacheName);    }

 认证是不想缓存的,登陆的时候查询一下数据库也没有什么,所以设置了 false,授权是要缓存的,也指定了缓存的名称,主要是为了刷新用户的权限缓存.
这样用户每次校验用户的访问权限,就不需要再查询数据库了.

 对于缓存的刷新,shiro也提供了方法,接着上例说,管理员修改了一个角色的访问权限,这个时候需要对缓存刷新.

 在 org.springrain.demo.service.impl.UserRoleMenuServiceImpl中进行了缓存手动刷新:

    public void updateRoleMenu(String roleId,String[] menus) throws Exception {        //刷新权限缓存        shiroCacheManager.getCache(GlobalStatic.authorizationCacheName).clear();        .......    }

以上就是对shiro cahce的简单使用.


出自weicms.net。

永久链接: http://www.weicms.net/2013/12/15/springrain4-shiro-cache.html

原创粉丝点击