ehcache缓存
- 他说hibernate框框默认使用的缓存技术
如何使用ehcache呢?
- 首先导入ehcache的依赖(用的是gradle)
compile group: 'net.sf.ehcache', name: 'ehcache', version: '2.10.4'
- 配置缓存的配置文件(ehcache.xml) ——放在resources目录下
<?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="D:\ehcacheData"/>
<!--
defaultCache,是默认的缓存策略 如果你指定的缓存策略没有找到,那么就用这个默认的缓存策略
maxElementsInMemory:内存中允许存储的最大元素个数,0代表无限
eternal:设置缓存中的对象是否为永久有效,如果是超时设置将被忽略,对象从不过期
根据存储数据不同,例如超静态不变的数据如省市区设置为永久不过期。
overflowToDisk:内存不足时,是否启用磁盘缓存
diskPersistent:是否启用磁盘持久化的机制,在jvm崩溃的时候和重启之间
timeToIdleSeconds:对象的最大的闲置的时间,如果超出闲置的时间,可能就会过期,单位:秒
当eternal=false对象不是永久有效时使用,可选属性,默认值是0。也就是可闲置时间无穷大。
timeToLiveSeconds:对象最多存活的时间 单位:秒 当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是存活时间无穷大
memoryStoreEvictionPolicy:当缓存数量达到了最大的指定条目数的时候,需要采用一定的算法,从缓存中清除一批数据,LRU,最近最少使用算法,最近一段时间内,最少使用的那些数据,就被干掉了
-->
<defaultCache
maxElementsInMemory ="1000"
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- helloworld缓存 -->
<cache name="HelloWorldCache"
maxElementsInMemory="1"
eternal="false"
timeToIdleSeconds="5000"
timeToLiveSeconds="5000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
- 测试并使用缓存
package com.lkl.jsp.ehcache;
import com.lkl.jsp.model.Dog;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class CacheTest {
public static void main(String[] args) {
//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();
//关闭缓存管理器
cacheManager.shutdown();
}
}
上面代码使用的Dog的实体类。
package com.lkl.jsp.model;
public class Dog {
private Long id;
private String type;
private short age;
public Dog(Long id, String type, short age) {
this.id = id;
this.type = type;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public short getAge() {
return age;
}
public void setAge(short age) {
this.age = age;
}
}