How to have multiple cache manager configuration in spring cache java

Rekha picture Rekha · Jul 25, 2016 · Viewed 27.4k times · Source

I want to have multiple spring cache managers configured in my web-application and I would be able to use different cache manager at various places in my project. Is there any way to do this.

Answer

Stephane Nicoll picture Stephane Nicoll · Aug 15, 2016

There are several ways you can do this and the right answer depends on your usage of the cache.

You have a "main" cache manager

If you use CacheManager A for 90% of your use case and B for 10% I'd advise to create a default CacheManager for A (you'll need to specify it via a CacheConfigurerSupport extension), something like:

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    @Override
    @Bean // not strictly necessary
    public CacheManager cacheManager() { ... CacheManager A }

    @Bean
    public CacheManager bCacheManager() { ... CacheManager B }
}

Then for the 10% use case you add a CacheConfig at the top of the classes that need to use the other cache manager

@CacheConfig(cacheManager="bCacheManager")
public class MyService { /*...*/ }

If you need to use the other cache manager for only one method, you can specify that at method level as well

@Cacheable(cacheNames = "books", cacheManager = "bCacheManager")
public Book findById(long id) { /*...*/ }

More fine grained resolution

If you're not in this situation, you need a way to know which cache manager needs to be used on a case-by-case basis. You can do that based on the target type (MyService) or the name of the cache (books). You'll need to implement a CacheResolver that does that translation for you.

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    @Override
    public CacheResolver cacheResolver() { ... }
}

Check the javadoc of CacheResolver for more details. In the implementation, you may have several CacheManager instances (either as bean or not) that you'll call internally based on your logic to determine which manager should be used.

I saw in a comment that you were referring to "module". Caching is really an infrastructure matter so I'd strongly advice you to move that decision at the application level. You may tag cache as being "local" and others being "clustered". But you should probably have some kind of nomenclature for the name to make it easier. Don't choose a cache manager at the module level.

this blog post illustrates this with other examples.