使用shiro+ehcache进行缓存权限数据

来源:互联网 发布:淘宝售后可以申请几次 编辑:程序博客网 时间:2024/06/07 22:24

首先,ehcache是一个纯java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

第一步、导入ehcache的jar包

<dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache-core</artifactId><version>2.6.6</version></dependency>

第二步、复制ehcache配置文件到项目中

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"><!-- 溢出到磁盘的目录 -->    <diskStore path="java.io.tmpdir"/>   <!-- 存储最大对象数 -->   <!-- 是否永久保存 -->   <!-- 最大空闲时间  单位:秒 -->   <!-- 存活时间 -->   <!-- 溢出到磁盘 -->   <!-- 磁盘上最大存储的对象数 -->   <!-- 服务器重启后磁盘上的数据是否有效 -->   <!-- 每隔多长时间去开启一次线程清理数据 -->   <!-- 淘汰策略    最近一段时间利用率低的会被优先清理掉 -->    <defaultCache                maxElementsInMemory="10000"            eternal="false"            timeToIdleSeconds="120"            timeToLiveSeconds="120"            overflowToDisk="true"            maxElementsOnDisk="10000000"            diskPersistent="false"            diskExpiryThreadIntervalSeconds="120"            memoryStoreEvictionPolicy="LRU"            /></ehcache>
第三步、注册ehcache缓冲管理器并注册到安全管理器中
<!-- 注册ehcache缓存管理器 --><bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"><!-- 注册配置文件的路径 --><property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property></bean>

<!-- 配置shiro框架的安全管理器 --><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><!-- 在安全管理器中注入realm --><property name="realm" ref="bosRealm"></property><!-- 在安全管理器中注入缓存管理器 --><property name="cacheManager" ref="cacheManager"></property></bean>

注意:上面设置的自动空闲时间为120秒,也就是说俩分钟之内使用的权限数据会缓存下来,并且在俩分钟内再次使用无需发送sql语句。空闲俩分钟后再次使用缓存的数据

后会无效,需要再次发送sql查询。用户退出后缓存的权限数据也是会立即失效的。

原创粉丝点击