如何在不覆盖默认 spring-cache 的情况下创建辅助 CacheManager

我的 application.yml 中有一个默认的 redis 缓存配置:


cache:

    type: redis

    redis:

      time-to-live: 7200000 # 2 hour TTL - Tune this if needed later

  redis:

    host: myHost

    port: myPort

    password: myPass

    ssl: true

    cluster:

      nodes: clusterNodes

    timeout: 10000

它工作得很好,我不想为它创建任何自定义缓存管理器。


但是,我的代码中有一些缓存不需要使用 redis。出于这个原因,我想制作第二个 CacheManager,它是一个简单的 ConcurrentHashMap 并使用 @Cacheable 指定它


为此,我创建了一个新的 CacheManager Bean:



@Configuration

@EnableCaching

@Slf4j

class CachingConfiguration {


    @Bean(name = "inMemoryCache")

    public CacheManager inMemoryCache() {

        SimpleCacheManager cache = new SimpleCacheManager();

        cache.setCaches(Arrays.asList(new ConcurrentMapCache("CACHE"));

        return cache;

    }


}

这导致 inMemoryCache 成为我的默认缓存,而我所有其他 @Cacheable() 都尝试使用 inMemoryCache。我不希望我创建的 CacheManager bean 成为我的默认值。无论如何我可以指定它是次要的并且不阻止 spring-cache 做它的魔法吗?


萧十郎
浏览 140回答 1
1回答

湖上湖

我能够保留 yml 中的默认 Redis 配置,并使用以下代码添加一个新的 inMemory CacheManager(我使用的是 Clustered Redis):&nbsp; &nbsp; @Bean&nbsp; &nbsp; @Primary&nbsp; &nbsp; public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory) {&nbsp; &nbsp; &nbsp; &nbsp; RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();&nbsp; &nbsp; &nbsp; &nbsp; redisCacheConfiguration.usePrefix();&nbsp; &nbsp; &nbsp; &nbsp; return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .cacheDefaults(redisCacheConfiguration).build();&nbsp; &nbsp; }&nbsp; &nbsp; @Bean&nbsp; &nbsp; public LettuceClusterConnection getConnection(LettuceConnectionFactory lettuceConnectionFactory) {&nbsp; &nbsp; &nbsp; &nbsp; LettuceClusterConnection clusterConnection = (LettuceClusterConnection) lettuceConnectionFactory.getClusterConnection();&nbsp; &nbsp; &nbsp; &nbsp; return clusterConnection;&nbsp; &nbsp; }&nbsp; &nbsp; @Bean(name = "inMemoryCache")&nbsp; &nbsp; public CaffeineCacheManager inMemoryCache() {&nbsp; &nbsp; &nbsp; &nbsp; CaffeineCacheManager cacheManager =&nbsp; new CaffeineCacheManager();&nbsp; &nbsp; &nbsp; &nbsp; cacheManager.setCaffeine(caffeineCacheBuilder());&nbsp; &nbsp; &nbsp; &nbsp; return cacheManager;&nbsp; &nbsp; }&nbsp; &nbsp; Caffeine< Object, Object > caffeineCacheBuilder() {&nbsp; &nbsp; &nbsp; &nbsp; return Caffeine.newBuilder()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .initialCapacity(3000)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .maximumSize(40000)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .expireAfterAccess(30, TimeUnit.MINUTES);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java