EhCache, this is enough

Posted by Seitan on Sat, 01 Jan 2022 17:01:28 +0100

1, Introduction
EhCache is a pure Java in-process caching framework, which is fast and lean. EhCache supports stand-alone cache and distributed cache. Distributed cache can be understood as the sharing of cache data, which leads to the small amount of memory cache data. EhCache stores and reads very fast.

The main advantages are:

fast
simple
Multiple cache strategies: heap cache, disk cache and cluster cache
There are two levels of cached data:, so there is no need to worry about capacity
Cached data is written to disk during virtual machine restart
Distributed caching can be implemented through RMI, pluggable API, etc
Listening interface with cache and cache manager
Support multiple cache manager instances and multiple cache areas of an instance
Provide cache implementation of Hibernate
2, Detailed configuration
1. Introduce dependency

net.sf.ehcache ehcache 2.10.4
2. Create a new configuration file 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">
   <!-- 
         Disk storage:Temporarily unused objects in the cache,Transfer to hard disk,be similar to Windows Virtual memory of the system
          path:Specifies the path to store objects on the hard disk
   -->
  <!-- Disk cache location -->
  <diskStore path="java.io.tmpdir/ehcache"/>
 <!-- 
        defaultCache:Default cache configuration information,If no special instructions are added,All objects are processed according to this configuration item
   -->
  <!-- Default cache -->
  <defaultCache
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          maxEntriesLocalDisk="10000000"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
  </defaultCache>
 <!--     
                 Each familiar meaning
                 name Cache space name (non cache) key)
        maxElementsInMemory: Set the upper limit of the cache,How many record objects can be stored at most
                maxElementsOnDisk: The maximum number of cache objects in the hard disk. If 0, it means infinity
                eternal: true Indicates that the object never expires and is ignored timeToIdleSeconds and timeToLiveSeconds Property, default to false  
                overflowToDisk: true Indicates that when the number of objects cached in memory reaches maxElementsInMemory After the limit, the overflow object will be written to the hard disk cache. Note: if the cached object is to be written to the hard disk, the object must be implemented Serializable Interface.
                diskSpoolBufferSizeMB: Disk cache size, default is 30 MB. each Cache Each should have its own cache.  
                diskPersistent: Whether to cache virtual machine restart period data, set to true Indicates the cache of virtual machine restart data  
                diskExpiryThreadIntervalSeconds: The running time interval of disk failure thread is 120 seconds by default 
                timeToIdleSeconds:  Sets the maximum time, in seconds, that an object is allowed to be idle. If the object has been idle for more than since it was last accessed timeToIdleSeconds Property value, the object will expire, EHCache It will be emptied from the cache. Only when eternal Attribute is false,This attribute is valid. If the property value is 0, it means that the object can be idle indefinitely 
                timeToLiveSeconds: Sets the maximum time, in seconds, that an object is allowed to exist in the cache. If the object has been in the cache for more than timeToLiveSeconds Property value, the object will expire, EHCache It will be cleared from the cache. Only when eternal Attribute is false,This attribute is valid. If the property value is 0, it means that the object can exist in the cache indefinitely. timeToLiveSeconds Must be greater than timeToIdleSeconds Attributes make sense  

            memoryStoreEvictionPolicy: When reached maxElementsInMemory When restricted, Ehcache The memory will be cleaned according to the specified policy. The optional strategies are: LRU(Least recently used, default policy) FIFO(First in first out) LFU(Minimum number of visits).
     -->
  <!-- helloworld cache -->
  <cache name="HelloWorldCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="600"
         timeToLiveSeconds="600"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>

3. If 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();
    }
}

Set cache

/**
 * Set local memory
 *
 * @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);
    }
}

Get local cache

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 will not actively clear the expired cache, but use scheduled tasks to clear the cache

/**
 * Periodically clear expired local cache
 **/
@Slf4j
@Configuration
@EnableScheduling
public class ExpireLocalCacheScheduler {

   @Qualifier("ehCacheManager")
    private CacheManager ehCacheManager

    /**
     * 10 Clear once per minute
     */
    @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);
        }
    }

}

To sum up, ehcache is the cache of java memory structure. The internal structure is the rewriting of java ConcurrentHashMap. The internal structure of ehcache3 is concurrenthashmap + weekreference

The author believes that ehcache is suitable for two services

1. There are many visits and qps, which is similar to the web brushing strategy

2. Small amount of data needs to be cached

Disadvantages:

If ehcache cluster is not used, sensitive data may not be updated in time when the project cluster is deployed.

1. ehcache is not used for sensitive data

2. If you use the recommended ehcache, set the expiration time to a very small 1-10 seconds
--------
Copyright notice: This is the original article of CSDN blogger "qq_996703282", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/qq_37391229/article/details/118522247