EhCache 是一个纯Java 进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认 CacheProvider。Ehcache 是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE 和 轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个 gzip缓存 servlet过滤器,支持REST和SOAP api等特点
Spring 提供对缓存功能的抽象,即允许绑定不同的缓存解决方案 (如 Ehcache),但本身不直接提供缓存功能的实现,它支持注解方式使用缓存,非常方便
特性 :
1> 快速
2> 简单
3> 多种缓存策略
4> 缓存数据有两级 : 内存和磁盘,因此无需担心容量问题
5> 缓存数据会在虚拟机重启的过程中写入磁盘
6> 可以通过 RMI、可插入API等方式进行分布式缓存
7> 具有缓存和缓存管理器的侦听接口
8> 支持多缓存管理器实例,以及一个实例的多个缓存区域
9> 提供 Hibernate 缓存实现
集成 : 可以单独使用,一般在第三方库中被用到的比较多 (如 mybatis、shiro等) ehcache 对分布式支持不够好,多个节点不能同步,通常和 redis一块使用
ehcache 和 redis 比较 :
1> ehcache 直接在 JVM 中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便
2> redis 是通过 socket访问到缓存服务,效率比 ecache低,比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案。如果是单个应用或者对缓存访问要求很高的应用,用ehcache。如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的,建议用 redis
ehcache也有缓存共享方案,不过是通过 RMI 或者 Jgroup多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适
需要依赖的库
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
简单 Demo
`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="java.io.tmpdir/ehcache"/>
<!-- 默认缓存 策略 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- helloworld缓存 策略 -->
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
`Dog.Java
public class Dog {
private long id;
private String name;
private int age;
public Dog(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{id=" + id + ", name='" + name + '\'' + ", age=" + age + '}';
}
}
`Java
// 1. 创建缓存管理器
CacheManager cacheManager = CacheManager.create("/Users/chenshun131/Desktop/AllMyFile/Study_CodeRepository/GitHub/PaySystem/common/pay-common/src/test/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", 2);
Element element2 = new Element("taidi", dog);
cache.put(element2);
// 获取对象数据
Element value2 = cache.get("taidi");
Dog dog2 = (Dog) value2.getObjectValue();
System.out.println(dog2.toString());
System.out.println(cache.getSize());
// 7. 刷新缓存
cache.flush();
// 8. 关闭缓存管理器
cacheManager.shutdown();
xml 配置文件
diskStore : ehcache支持内存和磁盘两种存储
path : 指定磁盘存储的位置
defaultCache : 默认的缓存策略
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
cache : 自定的缓存策略,当默认的配置不满足实际情况时可以通过自定义 (可以包含多个cache节点)
name : 缓存的名称,可以通过指定名称获取指定的某个Cache对象
maxElementsInMemory : 内存中允许存储的最大的元素个数,0代表无限个
clearOnFlush : 内存数量最大时是否清除
eternal : 设置缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。根据存储数据的不同,例如一些静态不变的数据如省市区等可以设置为永不过时
timeToIdleSeconds : 设置对象在失效前的允许闲置时间 (单位:秒)。仅当 eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
timeToLiveSeconds : 缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间
overflowToDisk : 内存不足时,是否启用磁盘缓存
maxEntriesLocalDisk : 当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中
maxElementsOnDisk : 硬盘最大缓存个数
diskSpoolBufferSizeMB : 这个参数设置DiskStore(磁盘缓存) 的缓存区大小,默认是30MB,每个Cache都应该有自己的一个缓冲区
diskPersistent : 是否在 VM 重启时存储硬盘的缓存数据,默认值是 false
diskExpiryThreadIntervalSeconds : 磁盘失效线程运行时间间隔,默认是120秒
EhCache 也可以通过代码来设置缓存策略
Spring 整合
添加 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="java.io.tmpdir/ehcache"/>
<!-- 默认缓存 策略 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- helloworld缓存 策略 -->
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
<cache name="UserCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
spring-ehcache.xml 将 ehcache 加入到 Spring 中,并开启缓存注解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<description>ehcache缓存配置管理文件</description>
<!-- 启用缓存注解开关 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"/>
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
</beans>
使用缓存的 Service 实现类,通过使用缓存注解来标记要缓存数据的方法
@CacheConfig(cacheNames = "HelloWorldCache")
public class EhcacheServiceImpl implements EhcacheService {
// value的值和ehcache.xml中的配置保持一致
@Cacheable(key = "#param")
@Override
public String getTimestamp(String param) {
Long timestamp = System.currentTimeMillis();
return timestamp.toString();
}
@Cacheable(key = "#key")
@Override
public String getDataFromDB(String key) {
System.out.println("从数据库中获取数据...");
return key + ":" + String.valueOf(Math.round(Math.random() * 1000000));
}
@CacheEvict(value = "HelloWorldCache", key = "#key")
@Override
public void removeDataAtDB(String key) {
System.out.println("从数据库中删除数据");
}
@CachePut(value = "HelloWorldCache", key = "#key")
@Override
public String refreshData(String key) {
System.out.println("模拟从数据库中加载数据");
return key + "::" + String.valueOf(Math.round(Math.random() * 1000000));
}
@Cacheable(value = "UserCache", key = "'user:' + #userId")
public User findById(String userId) {
System.out.println("模拟从数据库中查询数据");
return new User("1", "mengdee");
}
@Cacheable(value = "UserCache", condition = "#userId.length()<12")
public boolean isReserved(String userId) {
System.out.println("UserCache:" + userId);
return false;
}
// 清除掉UserCache中某个指定key的缓存
@CacheEvict(value = "UserCache", key = "'user:' + #userId")
public void removeUser(String userId) {
System.out.println("UserCache remove:" + userId);
}
// 清除掉UserCache中全部的缓存
@CacheEvict(value = "UserCache", allEntries = true)
public void removeAllUser() {
System.out.println("UserCache delete all");
}
}