shiro 之 Cache

来源:互联网 发布:java获取服务器ip地址 编辑:程序博客网 时间:2024/06/07 06:11

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。