第一步:定義一個ehcache.xml
<?xml version=”1.0” encoding=”utf-8”>
<ehcache>
<defaultCache
maxEntriesLocalHeap=”100”
eternal=”false”
timeToIdleSeconds = “120”
maxEntriesLocalDisk=”100000”
diskExpiryThreadIntervalSeconds=”120”
memoryStoreEvictionPolicy=”LRU”
>
<persistence strategy=”localTempSwap”>
</defalutCache>
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
</ehcache>
第二步:導入依賴
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2</version>
</dependency>
第三步: @Configuration
@PropertySource(value={“classpath:application.properties”},encoding=”utf-8”)
定義一個類 在類里面添加一個方法
@Bean
Public CacheManger getCacheManger(){
ClassPathResource classPathResource = new ClassPathResource(“ehcache,xml”)
Try{
cacheManger = CacheManger.create(classPathResource.getInputStream)
}catch(Exception e){
}
return cacheManger
}
第四步: //封裝cache方法
// 1. 創建緩存管理器
CacheManager cacheManager = CacheManager.create("./src/main/resources/ehcache.xml");
// 2. 獲取緩存對象
Cache cache = cacheManager.getCache("HelloWorldCache");
// 3. 創建元素
Element element = new Element("key1", "value1");
// 4. 將元素添加到緩存
cache.put(element);
// 5. 獲取緩存
Element value = cache.get("key1");
System.out.println(value);
System.out.println(value.getObjectValue());
// 6. 刪除元素
cache.remove("key1");
Dog dog = new Dog(1L, "taidi", (short)2);
Element element2 = new Element("taidi", dog);
cache.put(element2);
Element value2 = cache.get("taidi");
Dog dog2 = (Dog) value2.getObjectValue();
System.out.println(dog2);
System.out.println(cache.getSize());
// 7. 刷新緩存
cache.flush();
// 8. 關閉緩存管理器
cacheManager.shutdown();