Is it possible to use Caffeine's CacheLoader::loadAll
with @Cacheable
annotated method with collection parameter, like
@Cacheable(cacheNames = "exampleCache", cacheManager="exampleCacheManager", keyGenerator = "complexKeyGenerator")
List<String> getItems(List<String> keys, String commonForEveryKey) {
return ...
}
@Component
class ComplexKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
return ((List<String>)params[0]).stream()
.map(item -> new ComplexKey(item, (String) params[1]))
.collect(Collectors.toList());
}
}
@Data
@AllArgsConstructor
class ComplexKey {
String key;
String commonGuy;
}
class CustomCacheLoader implements CacheLoader<ComplexKey, String> {
@Override
public @Nullable String load(@NonNull ComplexKey key) throws Exception {
return loadAll(List.of(key)).get(key);
}
@Override
public @NonNull Map<@NonNull ComplexKey, @NonNull String> loadAll(@NonNull Iterable<? extends @NonNull ComplexKey> keys)
throws Exception {
return ...
}
}
@Bean
CacheManager exampleCacheManager(LoadingCache exampleCache) {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.registerCustomCache("exampleCache", exampleCache());
return cacheManager;
}
@Bean
Cache<Object, Object> exampleCache() {
return Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(1, TimeUnit.HOURS)
.recordStats()
.build(new CustomCacheLoader());
}
Looks like Spring Cache invokes CustomCacheLoader::load
instead of CustomCacheLoader::loadAll
and fails on ClassCastException
since it cannot cast collection of keys into single key.
What else should I configure to make it work?
getAll
method for retrieving data. If you need such a source code example please notify me. – Athabaska