Caching (Caffeine) & Spring - 基于方法参数值的两种缓存

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

我对使用 Caffeine 在 spring 中进行缓存有疑问。

我有一个缓存配置:

@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();
    }

}

还有一个@Cachaeble方法:

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

现在,group值是预定义的,只能是group1group2,以后会添加group3

是否可以根据String group值来配置这个缓存机制,所以当String groupgroup1someDataCache1someDataCache1时,将使用someDataCache1String groupgroup2 等时使用?

您可以添加多个 conditional @Cacheable annotations to the @Caching 注释。

@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);
}