Spring Data Store Redis - Use Multiple Caches

4.7k views Asked by At

I have an application that is made up of two web servers, two redis caches, and a backend store. The two web servers, and two redis caches are located on the West and East coasts, in order to optimize performance. So far I have been able to connect to my first cache, from my web servers, and to my backend store. But I am looking for a way to use Spring to push data to both redis caches. I have configured both of my RedisManagers as follows.

@Bean(name="CacheManager1")
public RedisCacheManager cacheManager() {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
    redisCacheManager.setTransactionAware(true);
    redisCacheManager.setLoadRemoteCachesOnStartup(true);
    redisCacheManager.setUsePrefix(true);
    return redisCacheManager;
}

@Bean(name="CacheManager2")
public RedisCacheManager cacheManager2() {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate2());
    redisCacheManager.setTransactionAware(true);
    redisCacheManager.setLoadRemoteCachesOnStartup(true);
    redisCacheManager.setUsePrefix(true);
    return redisCacheManager;
}

Now I have tried a few random ways to cache to both places, but this particular way is failing with "Cacheable is not a Repeatable Annotation"

@Cacheable(cacheManager = "CacheManager1", value = "activityProfile", key = "#id")
@Cacheable(cacheManager = "CacheManager2", value = "activityProfile", key = "#id")
public ActivityProfile findActivityProfile(String id) {
    return activityProfileRepository.findOne(id);
}

Is there any simple way to use Spring for this?

1

There are 1 answers

2
John Blum On BEST ANSWER

Dan Ciborowski - See here...

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#cache-annotations-caching

The Spring reference explains how to combine multiple Spring Cache Abstraction annotations (e.g. @Cacheable, @CachePut, etc) using @Caching.

So for cacheable you may do the following.

    @Caching(cacheable = {@Cacheable("CacheManager1"), @Cacheable("CacheManager2")})
    public ActivityProfile findActivityProfile(String id) {
        return activityProfileRepository.findOne(id);
    }