Home > OS >  Caching (Caffeine) & Spring - two caches based on method parameter value
Caching (Caffeine) & Spring - two caches based on method parameter value

Time:03-03

I have a question about caching in spring using Caffeine.

I have a cache configuration:

@Configuration
public class CaffeineCacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager(
                "someDataCache1",
                "someDataCache2");
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine<Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .initialCapacity(100)
                .maximumSize(200)
                .expireAfterWrite(1, TimeUnit.DAYS)
                .recordStats();
    }

}

And a @Cachaeble method:

@Override
@Cacheable
public List<SomeData> getSomeData(String group) {
    return someService.getSomeDataForGroup(group);
}

Now, the group values are predefined, they can only be group1, group2 and group3 will be added in the future.

Can this caching mechanism be configured basing on String group value, so someDataCache1 will be used when String group will be group1 and someDataCache1 will be used when String group is group2 etc?

CodePudding user response:

You can add multiple conditional @Cacheable annotations to the @Caching annotation.

@Caching(cacheable = {
        @Cacheable(cacheNames = "someDataCache1", condition = "#group.equals('group1')"),
        @Cacheable(cacheNames = "someDataCache2", condition = "#group.equals('group2')")
})
public List<String> getSomeData(String group) {
    return someService.getSomeDataForGroup(group);
}
  • Related