1

Have two classes, both annotating with @Cacheable (org.springframework.cache.annotation.Cacheable), either methods or class. I think it doesn't matter for this question.

Example:

@Cacheable(value = STATE_CACHE_NAME, key = "#root.methodName + '-' + #country?.id ?: \"null\" + '-' + #stateName ?: \"null\"")
public Long getStateId(CountryEntity country, String stateName) {...}

In some classes I'd like to use the simple in-memory cache and others the Redis cache. Both are configured in Spring boot auto-configure CacheConfigurations. How do I state this intent and use the different configurations?

1 Answer 1

2

@Cacheable takes a parameter "cacheManager", which lets you specify which bean of CacheManager it refers to.

So you'd add it with the name of the bean of your wanted CacheManager.

@Cacheable(cacheManager = "inMemoryCache", value = STATE_CACHE_NAME, key = "#root.methodName + '-' + #country?.id ?: \"null\" + '-' + #stateName ?: \"null\"")
public Long getStateId(CountryEntity country, String

You can either use the name of the bean method, or provide the name via the "name" parameter of @Bean.

E.g.

@Bean(name = "inMemoryCache")
CacheManager cacheManager() {
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks David. This solution requires me to create a specific instance of an in-memory cache in the method implementation. I'd like to use an autowired version of the in-memory cache, like I do with Redis.
@AlikElzin-kilaka I'm not sure I'm getting what you mean, can you edit your question with more details?
@david-gomez, updated the question and upvoted as it's still a valueble answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.