Issue
In my Java app that based on Spring Boot, I am trying to implement a caching mechanism for the following service method:
@Override
public List<EmployeeDTO> findAllByCountry(Country country) {
final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList
= countryRepository...
// code omitted for brevity
}
After several examples regarding to this issue, I decided on the approach mentioned on A Guide To Caching in Spring.
However, I am a little bit confused as it contains Spring and Spring Boot implementations and uses different annotation examples. I think I should start from 3.1. Using Spring Boot section as I use Spring Boot, but I am not sure about which Caching Annotation I should use (4.1. @Cacheable seems to be ok but I am not sure).
So, where should I put SimpleCacheCustomizer
and how can I apply that approach for my service method above (findAllByCountry
)? Any simple example would really be appreciated as I am new in Spring.
Solution
You don't need any customizations if you are a starter, and you want only the basics then do the following
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
}
The provided article states, return new ConcurrentMapCacheManager("addresses");
but you can use the default constructor and the relevant cache for adresses will be created later with @Cacheable("addresses")
. So no need for this to be in configuration.
You also need
@Cacheable("employeesList")
@Override
public List<EmployeeDTO> findAllByCountry(Country country) {
final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList
= countryRepository...
// code omitted for brevity
}
ready to go, that is the basic setup
Answered By - Panagiotis Bougioukos