shiro 之 Cache

本文介绍了Shiro的Cache功能,包括其作为Shiro组件间缓存服务的概念、应用场景,如Realm和Session管理。Shiro的Cache设计允许使用各种缓存产品作为后端,如ehcache或Redis。在Realm中,认证和授权信息会被缓存,提高性能。在Session管理中,通过配置CacheManager,可以优化Session的存储和检索。总之,Shiro Cache提供了灵活的缓存解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

shiro 之 Cache

本节将学习以一下Shiro 的核心功能之一 Cache。关于Shiro 的 Cache 我再次先声明一下下:Shiro 的Cache 的服务范围一般在Shiro 的服务内。关于缓存我们之前有学习过Redis,在一些Application中我们也是用到了 Redis作为缓存来处理数据。因而我们可以得出一个结论:其他缓存可以作为 Shiro 的缓存代理,但是Shiro 自身的缓存(比如ehcache)只能服务于Shiro(比如认证授权时的Subject和一些Session等。)


概念

  • Shiro Cache

    • 官方介绍

      • The CacheManager creates and manages Cache instance lifecycles used by other Shiro components. Because Shiro can access many back-end data sources for authentication, authorization and session management, caching has always been a first-class architectural feature in the framework to improve performance while using these data sources. Any of the modern open-source and/or enterprise caching products can be plugged in to Shiro to provide a fast and efficient user-experience.
    • 通常而言

      • Shiro提供了类似于Spring的Cache抽象,即Shiro本身不实现Cache,但是对Cache进行了又抽象,方便更换不同的底层Cache实现。Shiro Cache 常用于Authentication、Authorization和SessionManagement。

Shiro 提供了三种 Cache Abstract Interface

  • Cache

    package org.apache.shiro.cache;
    import java.util.Collection;
    import java.util.Set;
    
    public interface Cache<K, V> {
    
        public V get(K key) throws CacheException;
    
        public V put(K key, V value) throws CacheException;
    
        public V remove(K key) throws CacheException;
    
        public void clear() throws CacheException;
    
        public int size();
    
        public Set<K> keys();
    
        public Collection<V> values();
    }
    
  • CacheManager

    public interface CacheManager {
    
        public <K, V> Cache<K, V> getCache(String name) throws CacheException;
    }
  • CacheManagerAware: 将CacheManagerAware用于注入CacheManager

    public interface CacheManagerAware {
    
        void setCacheManager(CacheManager cacheManager);
    }
    

应用场景

Shiro 的Cache 使用的两大场景分别为 Realm 和 Session。

  • Realm 中的Cache。

    一般我们在实现自定义Realm是会 直接继承 AuthorizingRealm 即可。又因为AuthorizingRealm 继承(实际上是AuthorizingRealm 继承了 AuthenticatingRealm,而AuthenticatingRealm继承了CachingRealm)了CachingRealm,因而当用户在我们的自定义Realm做认证授权时,一些信息会被写入缓存。

    比如做认证时用户名会被写入Session中然后被写入缓存中,做授权(角色鉴定)时会把当前用户的角色写入缓存,下一次该用户访问被授权页面时Shiro 的SecurityManager 会优先从缓存中读取,如果缓存中没有则进行授权处理,授权处理完之后把用户信息写入缓存。

    下面我们学习一下 Shiro Cache 的配置。

    • 配置 cacheManager

      • 添加Shiro-ehcache依赖

        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.2.4</version>
        </dependency>
      • Context中的配置

        <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
            <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property>
        </bean>
  • ClasspPath下新建 ehcache.xml 文件

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache>
    
        <diskStore path="java.io.tmpdir" /> <!-- 缓存存放目录(此目录为放入系统默认缓存目录),也可以是”D:/cache“ java.io.tmpdir -->
    
        <!-- 一下所有时间默认单位:秒 -->
        <!-- 设置重登时间间隔 -->
        <cache name="passwordRetryCache"
               maxEntriesLocalHeap="2000"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
        <!-- 设置认证信息保留期限 -->
        <cache name="authorizationCache"
               maxEntriesLocalHeap="2000"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
        <!-- 设置授权信息保留期限 -->
        <cache name="authenticationCache"
               maxEntriesLocalHeap="2000"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
        <!-- Shiro Session缓存 -->
        <cache name="shiro-activeSessionCache"
               maxEntriesLocalHeap="2000"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
    
        <defaultCache maxElementsInMemory="10000" eternal="false"
            timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
            maxElementsOnDisk="10000000" diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
    
        <!-- name:Cache的唯一标识 maxElementsInMemory:内存中最大缓存对象数 maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大 
            eternal:Element是否永久有效,一但设置了,timeout将不起作用 overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中 
            timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大 
            timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大 
            diskPersistent:是否缓存虚拟机重启期数据 diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒 
            diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区 
            memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用) -->
    </ehcache>  
    
  • Session中的Cache

    如securityManager实现了SessionsSecurityManager,其会自动判断SessionManager是否实现了CacheManagerAware接口,如果实现了会把CacheManager设置给它。然后sessionManager会判断相应的sessionDAO(如继承自CachingSessionDAO)是否实现了CacheManagerAware,如果实现了会把CacheManager设置给它。

    例如在我们之前学习SessionDao时做的配置有体现:

    <!-- Shiro SessionDao -->
    <bean id="sessionDao" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <!--  -->
        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"></property>
        <property name="sessionIdGenerator" ref="sessionIdGenerator"></property>
        <property name="cacheManager" ref="cacheManager"></property>
    </bean>
    

    SessionDao中的 activeSessionsCacheName 使用的是 shiro-activeSessionCache,其属性我们已在ehcache.xml 有配置了。


小结

  • Shiro Cache 可以使用自身Cache 如 ehcache,也可以使用其他缓存如Redis等。

  • Shiro Cache 主要应用的两大场景为Realm 和 Session。

这是一个shiro的入门Demo.. 使用了Spring MVC,mybaits等技术.. 数据库设计 : User : name--password Role : id--userid--roleName Function : id--userid--url tinys普通用户只能访问index.jsp admin用户通过添加了admin的permission,所以可以访问admin.jsp role用户通过添加了role角色,所以可以访问role.jsp 这是最基本的shiro的运用..目的是让你快速了解shiro的机制.. 这个Demo体现shiro的地方主要在两个类以及shiro.xml的配置文件 CustomRealm : 处理了登录验证以及授权.. ShiroAction : 用来传递登录时的用户数据..转换为token传递给realm...之后根据结果做相应的逻辑处理.. shiro.xml : shiro的主要配置... 规则定义在以下地方 : /login.jsp* = anon /index.jsp* = authc /index.do* = authc /admin.jsp*=authc,perms[/admin] /role.jsp*=authc,roles[role] ------------------------------------------------------------------------------------------------------------------------------------------------------------- 2015-10-28更新 --通过添加了以下内容来使用注解方式配置权限.... unauth login --修改了过滤链 //简单的讲就是把需要特别处理的路径写到前面,越特殊写到越前 /shiro/login.do*=anon /login.jsp* = anon /admin.jsp*=authc,perms[/admin] /role.jsp*=authc,roles[role] /** = authc --------------------------------------------------------------------------------------------------------------------------------------------------- 15-10-29 添加了使用ehcache缓存机制 添加了redis缓存...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值