How to create a secondary CacheManager without overriding default spring-cache

Guilherme Rodriguez :

I have a default redis cache configuration in my application.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

It works great and I don't want to create any custom cache manager for it.

However, there are some caches in my code where using redis is not necessary. For that reason, I want to make a second CacheManager that's a simple ConcurrentHashMap and specify it with @Cacheable

To do that I created a new 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;
    }

}

This causes the inMemoryCache to be my default cache and all my other @Cacheable() tried to use the inMemoryCache. I don't want the CacheManager bean that I created to be my default. Is there anyway I can specify that it's secondary and not prevent spring-cache for doing it's magic?

Thanks!

Guilherme Rodriguez :

I was able to keep the default Redis configuration from the yml and add a new inMemory CacheManager with the following code (I'm using 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);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=124013&siteId=1