本文部分摘自http://www.cnblogs.com/jingmoxukong/p/5975994.html,感谢博主分享。
1 Ehcache是一个纯Java的进程内缓存框架,具有快速、精干等特点。它是Hibernate中的默认缓存框架。尝试写一个demo,并且在后面会与Spring进行整合。
1.1 Demo HelloWord。
src下ehcache.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘缓存位置 -->
<diskStore path="E:\ehcache"/>
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<!-- helloworld缓存 -->
<cache name="helloworld"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
测试:
/**
* 测试
*/
public static void demoText01(){
final CacheManager cacheManager = new CacheManager();
//根据ehcache配置文件中的配置缓存名称加载指定的缓存空间
final Cache cache = cacheManager.getCache("helloworld");
//创建一个键
final String key = "greeting";
//创建一个键值对
final Element putGreeting = new Element(key, "Hello, World!");
//添加数据至缓存中
cache.put(putGreeting);
//从缓存中读取数据
final Element getGreeting = cache.get(key);
System.out.println(getGreeting.getObjectValue());
}
1.2 创建CacheManager
public static void demoText02() {
// 使用Ehcache默认配置获取单例的CacheManager实例
CacheManager cacheManager01 = CacheManager.create();
//获取配置文件中的缓存名
String[] cacheName01 = cacheManager01.getCacheNames();
System.out.println("01:"+cacheName01[0]);
// 使用Ehcache默认配置新建一个CacheManager实例
CacheManager cacheManager02 = CacheManager.newInstance();
String[] cacheNames02 = cacheManager02.getCacheNames();
System.out.println("02:"+cacheNames02[0]);
// 使用指定的配置文件创建一个CacheManager实例
CacheManager manager1 = CacheManager.newInstance("./src/ehcache.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
System.out.println("03:"+cacheNamesForManager1[0]);
// 基于文件流得到配置文件,并创建CacheManager实例
InputStream fis = null;
try {
fis = new FileInputStream(new File("./src/ehcache.xml").getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if(fis!=null){
CacheManager manager03 = CacheManager.newInstance(fis);
String[] cacheName03=manager03.getCacheNames();
System.out.println("04:"+cacheName03[0]);
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.3 添加缓存
public static void demoText03(){
//除了可以使用xml文件中配置的缓存,你也可以使用API动态增删缓存
//创建一个管理器动态添加缓存
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("helloworld02");
// 使用默认配置添加缓存
singletonManager.addCache("testCache");
Cache cache01 = singletonManager.getCache("testCache");
// 使用自定义配置添加缓存,注意缓存未添加进CacheManager之前并不可用
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache cache02 = singletonManager.getCache("testCache");
// 使用特定的配置设置一个缓存
//缓存中最大节点数
int maxEntriesLocalHeap=1000;
//缓存名称
String cacheName="testCache";
CacheConfiguration cacheConfiguration=new CacheConfiguration(cacheName, maxEntriesLocalHeap);
cacheConfiguration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU);
cacheConfiguration.eternal(false);
cacheConfiguration.timeToLiveSeconds(60);
cacheConfiguration.timeToIdleSeconds(30);
cacheConfiguration.diskExpiryThreadIntervalSeconds(0);
cacheConfiguration.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP));
Cache testCache = new Cache(cacheConfiguration);
//添加缓存
singletonManager.addCache(testCache);
}
删除缓存
public static void demoText04(){
CacheManager singletonManager = CacheManager.create();
//根据名称移除指定的缓存
singletonManager.removeCache("sampleCache1");
}
2 与Spring整合:采用注解的方式。
@Cacheable
表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。这个注解可以用condition属性来设置条件,如果不满足条件,就不使用缓存能力,直接执行方法。可以使用key属性来指定key的生成规则。如下:
// @Cacheable可以设置多个缓存,形式如:@Cacheable({"books", "isbns"})
@Cacheable(value = "users", condition = "#user.getId() <= 2")
public User findUserInLimit(User user) {
return findUserInDB(user.getId());
}
@CachePut
与@Cacheable不同,@CachePut不仅会缓存方法的结果,还会执行方法的代码段。它支持的属性和用法都与@Cacheable一致。
@CacheEvict
与@Cacheable功能相反,@CacheEvict表明所修饰的方法是用来删除失效或无用的缓存数据。
@Caching
如果需要使用同一个缓存注解(@Cacheable、@CacheEvict或@CachePut)多次修饰一个方法,就需要用到@Caching。如下:
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)
@CacheConfig
与前面的缓存注解不同,这是一个类级别的注解。
如果类的所有操作都是缓存操作,你可以使用@CacheConfig来指定类,省去一些配置。如下:
@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {
@Cacheable
public Book findBook(ISBN isbn) {...}
}