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"?>

         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
   
  
  
 
  
  <defaultCache
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          maxEntriesLocalDisk="10000000"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU">
    
  
 
  
  
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="600"
         timeToLiveSeconds="600"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>

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