Dos formas de que ehcache aumente el dominio de caché

Dos formas de que ehcache aumente el dominio de caché

Método uno, configuración xml

1. Cree un nuevo archivo de configuración 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>

2. Cree una nueva instancia de CacheManager

        final InputStream inputStream = SpringConfig.class.getClassLoader().getResourceAsStream("ehcache.xml");
        // 默认读取类根路径(/src/main/resource)下的ehcache.xml配置文件
        net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.create(inputStream );

Método 2: programático (el dominio de caché se puede agregar dinámicamente)

package com.example.demo.config;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {
    
    

    /**
     * 与spring cache整合,对ehcache自身的net.sf.ehcache.CacheManager进行包装。
     */
    @Bean
    public CacheManager ehcacheCacheManager() {
    
    
        net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.create();
        // 手机验证码
        final Ehcache mobileCache = cacheManager.addCacheIfAbsent("mobileCache");
        final CacheConfiguration config = mobileCache.getCacheConfiguration();
        config.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
        config.setTimeToIdleSeconds(300);
        config.setTimeToLiveSeconds(300);
        config.setMaxEntriesInCache(10_000L);
        config.setMaxEntriesLocalDisk(10_000L);
        EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
        ehCacheCacheManager.setCacheManager(cacheManager);
        return ehCacheCacheManager;
    }

}

Extensión : puede encontrar las anotaciones especificadas a través del escaneo de paquetes y agregar cacheNames a net.sf.ehcache.CacheManager (singleton) para integrarse mejor con Spring Cache.

 public CacheManager ehcacheCacheManager() {
    
    
        net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.create();
        /*
          包扫描查找指定注解并将cacheNames添加到net.sf.ehcache.CacheManager(单例)
         */
        Reflections reflections = new Reflections("com.example.demo", new TypeAnnotationsScanner()
                , new SubTypesScanner(), new MethodAnnotationsScanner());

        Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(CacheConfig.class);
        for (Class<?> aClass : classesList) {
    
    
            final CacheConfig config = AnnotationUtils.findAnnotation(aClass, CacheConfig.class);
            if (config.cacheNames() != null && config.cacheNames().length > 0) {
    
    
                for (String cacheName : config.cacheNames()) {
    
    
                    cacheManager.addCacheIfAbsent(cacheName);
                }
            }
        }
        /*
          方法级别的注解 @Caching、@CacheEvict、@Cacheable、@CachePut,结合实际业务场景仅扫描@Cacheable即可
         */
        final Set<Method> methods = reflections.getMethodsAnnotatedWith(Cacheable.class);
        for (Method method : methods) {
    
    
            final Cacheable cacheable = AnnotationUtils.findAnnotation(method, Cacheable.class);
            if (cacheable.cacheNames() != null && cacheable.cacheNames().length > 0) {
    
    
                for (String cacheName : cacheable.cacheNames()) {
    
    
                    cacheManager.addCacheIfAbsent(cacheName);
                }
            }
        }
        EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
        ehCacheCacheManager.setCacheManager(cacheManager);
        return ehCacheCacheManager;
    }

Supongo que te gusta

Origin blog.csdn.net/ory001/article/details/109726298
Recomendado
Clasificación