【问题标题】:Set TTL fot caching different data with one CacheManager in Spring Boot在 Spring Boot 中使用一个 CacheManager 设置缓存不同数据的 TTL
【发布时间】:2021-04-27 03:02:23
【问题描述】:

我正在缓存来自三个不同外部源的响应,并且我正在使用相同的 CacheManager。我想为每个方法设置不同的TTL,也就是缓存,可以吗?

我也尝试设置多个缓存管理器,但出现异常 - 在预期只有 1 个时发现了 CachingConfigurer 的 2 个实现

这是我的 CacheConfig 类和我的 CacheManager - 这是我为我的经理配置的地方

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    private static final String CACHE_NAME = "transportLocations";

    // Here is "global" TTL for every result from the method
    private static final int TTL_SECONDS = 15;
    private static final int ENTRIES_LOCAL_HEAP = 1000;
    private static final String LRU = "LRU";

    @Bean
    public net.sf.ehcache.CacheManager ehCacheManager() {
        final var transportLocationCache = new CacheConfiguration();
        final var config = new net.sf.ehcache.config.Configuration();

        transportLocationCache.setName(CACHE_NAME);
        transportLocationCache.setMaxEntriesLocalHeap(ENTRIES_LOCAL_HEAP);
        transportLocationCache.setMemoryStoreEvictionPolicy(LRU);
        transportLocationCache.setTimeToLiveSeconds(TTL_SECONDS);
        config.addCache(transportLocationCache);

        return net.sf.ehcache.CacheManager.newInstance(config);
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }
}

这是我的服务,我在其中使用 Cacheable 注释。我有三种方法使用此注解,这就是我需要为每种方法设置不同 TTL 的地方。

@Cacheable(value = TRANSPORT_LOCATIONS, cacheManager = CACHE_MANAGER, key = ROOT_METHOD_NAME, sync = true)

你有什么建议吗,怎么做?

非常感谢。

【问题讨论】:

    标签: java spring-boot caching


    【解决方案1】:

    我使用了多个缓存管理器和缓存解析器。我按照这些教程进行操作。

    https://www.baeldung.com/spring-multiple-cache-managers

    https://www.baeldung.com/spring-boot-caffeine-cache

    【讨论】:

      【解决方案2】:

      为了使用特定于缓存的 TTL,您不必使用不同的缓存管理器。虽然 EhCache 和其他一些缓存提供程序使您可以使用专用 XML 进行配置,但对于内存提供程序,您可能需要配置每个缓存以及 CacheManager。

      更多详情请查看http://dolszewski.com/spring/multiple-ttl-caches-in-spring-boot/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-19
        • 2017-01-27
        • 2015-07-30
        相关资源
        最近更新 更多