EhCache看这一篇就够了

一、简介
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点。EhCache支持单机缓存和分布式缓存,分布式可以理解为缓存数据的共享,这就导致内存缓存数据量偏小。ehcache缓存非常存储和读取非常快。

主要优点有:

快速
简单
多种缓存策略 堆缓存、磁盘缓存、集群缓存
缓存数据有两级:,因此无需担心容量问题
缓存数据会在虚拟机重启的过程中写入磁盘
可以通过RMI、可插入API等方式进行分布式缓存
具有缓存和缓存管理器的侦听接口
支持多缓存管理器实例,以及一个实例的多个缓存区域
提供Hibernate的缓存实现
二、详细配置
1、引入依赖

net.sf.ehcache ehcache 2.10.4
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>

3、如果是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);
    }
}

获取本地缓存

public String getLocalCache(String key) {
    Cache cache = ehCacheManager.getCache("HelloWorldCache");
    if (cache == null) {
        return null;
    }
    Element cacheElement = cache.get(key);
    if (cacheElement == null) {
        return null;
    }
    return cacheElement.getObjectValue().toString();
}

4、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);
        }
    }

}

总结ehcache是java内存结构的缓存,内部结构为java ConcurrentHashMap的重写,ehcache3内部结构为ConcurrentHashMap+WeekRefererce

作者认为使用ehcache适合两种业务

1、访问次数多qps特别多,类似web放刷策略

2、需要缓存数据量小

缺点:

如果不使用ehcache集群,在项目集群部署的情况下,敏感数据的更新可能不及时。

1、敏感数据不使用ehcache

2、如果使用建议ehcache的过期时间设置的非常小1-10秒
————————————————
版权声明:本文为CSDN博主「qq_996703282」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_37391229/article/details/118522247

原文地址:https://www.cnblogs.com/ltian123/p/15745354.html