使用Shiro 的ehcache缓存权限数据最简单的入门教程

当前我们每次访问系统中经过权限控制的功能时,shiro框架会调用realm中的授权方法,导致频繁查询数据库。为了减轻这种没必要的系统资源浪费,我们决定在项目中使用Shio自带的ehcache解决这个问题

1 .在pom.xml中引入ehcache的坐标

<!-- 缓存 -->
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache-core</artifactId>
	<version>2.6.11</version>
</dependency>

2, 提供一个ehcache的配置文件(可以从jar包中获得)

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    
    <!-- 将权限数据写入内存  如果内存数据写满了,写到 磁盘配置目录中-->
    <!--磁盘存储的路径 临时文件目录-->
    <diskStore path="java.io.tmpdir"/>
    <!--maxElementsInMemory内存中最大允许创建的对象数-->
    <!--eternal内存中对象是否为永久的,如果是true,超时设置将被忽略,对象从不过期 -->
    <!--timeToIdleSeconds设置对象在它过期之前的空闲时间  可选属性,默认值是0,也就是可闲置时间无穷大-->
    <!--timeToLiveSeconds设置对象在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当对象不是永久有效时使用,默认是0.,也就是element存活时间无穷大-->
    <!--overflowToDisk配置此属性,当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中(必须要实现序列化接口)。-->
    <!--maxElementsOnDisk磁盘中最大缓存对象数,若是0表示无穷大-->
    <!--diskPersistent是否缓存虚拟机重启期数据。-->
    <!--diskExpiryThreadIntervalSeconds磁盘失效线程运行时间间隔,默认是120秒-->
    <!--memoryStoreEvictionPolicy当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)-->
    <!--overflowToDisk  -->
    <defaultCache maxElementsInMemory="10000"  
                eternal="false"							
            	timeToIdleSeconds="120"			
                timeToLiveSeconds="3600"			
                overflowToDisk="true"				
                maxElementsOnDisk="10000000"
                diskPersistent="false"			
                diskExpiryThreadIntervalSeconds="120" 
                memoryStoreEvictionPolicy="LFU" />
</ehcache>

3, 在spring配置文件中注册一个缓存管理器对象,并注入给安全管理器对象 

<!-- 注册安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	<property name="realm" ref="bosRealm"></property>
	<property name="cacheManager" ref="ehCacheManager"></property>
</bean>
<!-- 注册缓存管理器 -->
<bean id="ehCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
	<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property>
</bean>

 4 第一次测试时报序列化异常

这时后只需要让相关的实体类实现 implements Serializable实现虚拟化即可

猜你喜欢

转载自blog.csdn.net/luo609630199/article/details/81388873