本文介绍 Shiro + EHCache + Spring 的结合:
首先有两种方式来创建缓存实列
只介绍spring bean配置方式:
1、Spring EhCacheManagerFactoryBean方式创建。
2、EhCacheManager方式创建。
EHCache配置文件说明
1、EHCache 配置文件代码。
2、 EHCache 配置文件说明
<?xml version="1.0" encoding="UTF-8"?> <ehcache > <diskStore path="java.io.tmpdir"/> <!-- name Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里) maxElementsInMemory 内存中保持的对象数量 maxElementsOnDisk DiskStore中保持的对象数量,默认值为0,表示不限制 eternal 是否是永恒数据,如果是,则它的超时设置会被忽略 overflowToDisk 如果内存中数据数量超过maxElementsInMemory限制,是否要缓存到磁盘上 timeToIdleSeconds 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问 timeToLiveSeconds 对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问 diskPersistent 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false diskExpiryThreadIntervalSeconds 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次 diskSpoolBufferSizeMB DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore memoryStoreEvictionPolicy 如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU--> <cache name="authorizationCache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"> </cache> </ehcache>
ShiroCacheManager管理类。
ShiroCacheManager实现org.apache.shiro.cache.Cache接口,重写里面方法。
实例测试
看代码。
package com.ehcache.test; import org.apache.shiro.cache.Cache; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { //1、创建 Spring 的 IOC 容器 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //2、获取IOC容器中ShiroCacheManager实例 ShiroCacheManager<String, String> shiroCacheManager = (ShiroCacheManager<String, String>) ctx.getBean("shiroCacheManager"); Cache<String, String> cache = shiroCacheManager.getCache(); //3、保存 cache.put("key", "12"); System.out.println(cache.get("key")); System.out.println("***************************"); //4、 删除 cache.remove("key"); System.out.println(cache.get("key")); } }
本文暂时没有评论,来添加一个吧(●'◡'●)