如何创建辅助CacheManager而不覆盖默认的spring-cache

时间:2019-07-05 15:18:51

标签: java spring caching redis spring-cache

我的应用程序中有一个默认的redis缓存配置。yml:

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做魔术呢?

谢谢!

1 个答案:

答案 0 :(得分:0)

我能够保留yml中的默认Redis配置,并使用以下代码添加新的inMemory CacheManager(我正在使用Clustered Redis):

    @Bean
    @Primary
    public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration.usePrefix();


        return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory)
                .cacheDefaults(redisCacheConfiguration).build();
    }

    @Bean
    public LettuceClusterConnection getConnection(LettuceConnectionFactory lettuceConnectionFactory) {
        LettuceClusterConnection clusterConnection = (LettuceClusterConnection) lettuceConnectionFactory.getClusterConnection();
        return clusterConnection;
    }


    @Bean(name = "inMemoryCache")
    public CaffeineCacheManager inMemoryCache() {
        CaffeineCacheManager cacheManager =  new CaffeineCacheManager();
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine< Object, Object > caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .initialCapacity(3000)
                .maximumSize(40000)
                .expireAfterAccess(30, TimeUnit.MINUTES);
    }