基本介绍
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
Ehcache最初是由Greg Luck于2003年开始开发。2009年,该项目被Terracotta购买。软件仍然是开源,但一些新的主要功能(例如,快速可重启性之间的一致性的)只能在商业产品中使用,例如Enterprise EHCache and BigMemory。维基媒体Foundationannounced目前使用的就是Ehcache技术。
图示 Ehcache 在应用程序中的位置:
主要的特性有
1. 快速
2. 简单
3. 多种缓存策略
4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题
5. 缓存数据会在虚拟机重启的过程中写入磁盘
6. 可以通过RMI、可插入API等方式进行分布式缓存
7. 具有缓存和缓存管理器的侦听接口
8. 支持多缓存管理器实例,以及一个实例的多个缓存区域
9. 提供Hibernate的缓存实现
详细配置
1、引入依赖
net.sf.ehcache ehcache 2.10.0
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
2.新建配置文件 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">
<!--
磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
path:指定在硬盘上存储对象的路径
-->
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!--
defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
-->
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!--
各个熟悉的含义
name 缓存空间名称(非缓存key)
maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大
eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false
overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。
diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。
diskPersistent:是否缓存虚拟机重启期数据,设置成true表示缓存虚拟机重启期数据
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒
timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态
timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
-->
<!-- helloworld缓存 -->
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="600"
timeToLiveSeconds="600"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
如果是Spring boot工程
请按照以下进行设置:
@Configuration
public class CacheConfig {
//EhCacheManager
@Bean(name = "ehCacheManager")
public CacheManager cacheManager() {
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
cacheManagerFactoryBean.setShared(true);
cacheManagerFactoryBean.afterPropertiesSet();
return cacheManagerFactoryBean.getObject();
}
}
设置缓存
/**
* 设置本地内存
*
* @param key
* @return
*/
@Override
public void setLocalCache(String key, String value, Integer timeout) {
Cache cache = ehCacheManager.getCache("HelloWorldCache");
if (timeout == null) {
timeout = localCacheTimeout;
}
if (value != null) {
Element element = new Element(key, value);
element.setTimeToLive(timeout);
cache.put(element);
}
}
ehcache 2.x不会主动清楚过期缓存,使用定时任务清楚缓存
/**
* 定时清除过期本地缓存
**/
@Slf4j
@Configuration
@EnableScheduling
public class ExpireLocalCacheScheduler {
@Qualifier("ehCacheManager")
private CacheManager ehCacheManager
/**
* 10分钟清除一次
*/
@Scheduled(cron = "0 */10 * * * ?")
private void expiredLocalCache() {
try {
Cache cache = ehCacheManager.getCache("HelloWorldCache");
cache.getKeysWithExpiryCheck();
cache.evictExpiredElements()
} catch (Exception e) {
log.error("evictExpiredLocalCache error!", e);
}
}
}
@Scheduled注解详解
总结:
ehcache是java内存结构的缓存,内部结构为java ConcurrentHashMap的重写,ehcache3内部结构为ConcurrentHashMap+WeekRefererce
使用ehcache比较适合两种业务
1、访问次数多qps特别多,类似web放刷策略
2、需要缓存数据量小
缺点:
如果不使用ehcache集群,在项目集群部署的情况下,敏感数据的更新可能不及时。
1、敏感数据不使用ehcache
2、如果使用建议ehcache的过期时间设置的非常小1-10秒