shiro 之 Cache

朱雀 2022-06-06 13:09 258阅读 0赞

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

    1. package org.apache.shiro.cache;
    2. import java.util.Collection;
    3. import java.util.Set;
    4. public interface Cache<K, V> {
    5. public V get(K key) throws CacheException;
    6. public V put(K key, V value) throws CacheException;
    7. public V remove(K key) throws CacheException;
    8. public void clear() throws CacheException;
    9. public int size();
    10. public Set<K> keys();
    11. public Collection<V> values();
    12. }
  • CacheManager

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

    1. public interface CacheManagerAware {
    2. void setCacheManager(CacheManager cacheManager);
    3. }

应用场景

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

  • Realm 中的Cache。

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

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

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

    • 配置 cacheManager

      • 添加Shiro-ehcache依赖

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

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

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <ehcache>
    3. <diskStore path="java.io.tmpdir" /> <!-- 缓存存放目录(此目录为放入系统默认缓存目录),也可以是”D:/cache“ java.io.tmpdir -->
    4. <!-- 一下所有时间默认单位:秒 -->
    5. <!-- 设置重登时间间隔 -->
    6. <cache name="passwordRetryCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true">
    7. </cache>
    8. <!-- 设置认证信息保留期限 -->
    9. <cache name="authorizationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true">
    10. </cache>
    11. <!-- 设置授权信息保留期限 -->
    12. <cache name="authenticationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true">
    13. </cache>
    14. <!-- Shiro Session缓存 -->
    15. <cache name="shiro-activeSessionCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true">
    16. </cache>
    17. <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
    18. <!-- 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(较少使用) -->
    19. </ehcache>
  • Session中的Cache

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

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

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

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


小结

  • Shiro Cache 可以使用自身Cache 如 ehcache,也可以使用其他缓存如Redis等。
  • Shiro Cache 主要应用的两大场景为Realm 和 Session。

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读

    相关 shiro Cache

    shiro 之 Cache 本节将学习以一下Shiro 的核心功能之一 Cache。关于Shiro 的 Cache 我再次先声明一下下:Shiro 的Cache 的服务范