Spring CaffeineCacheManager中添加了多个Caffeine LoadingCaches [英] Multiple Caffeine LoadingCaches added to Spring CaffeineCacheManager
问题描述
我想在Spring CacheManager
中添加几个不同的LoadingCache
,但是我不知道使用CaffeineCacheManager
怎么可能.看来只有一个加载器才可以刷新内容,但是我需要为每个缓存使用单独的加载器.是否可以将多个加载缓存添加到Spring缓存管理器?如果是这样,那怎么办?
I'm looking to add several distinct LoadingCache
's to a Spring CacheManager
, however I don't see how this is possible using CaffeineCacheManager
. It appears that only a single loader is possible for refreshing content, however I need separate loaders for each cache. Is it possible to add multiple loading caches to a Spring cache manager? If so, then how?
CaffeineCacheManager cacheManage = new CaffeineCacheManager();
LoadingCache<String, Optional<Edition>> loadingCache1 =
Caffeine.newBuilder()
.maximumSize(150)
.refreshAfterWrite(5, TimeUnit.MINUTES)
.build(test -> this.testRepo.find(test));
LoadingCache<String, Optional<Edition>> loadingCache2 =
Caffeine.newBuilder()
.maximumSize(150)
.refreshAfterWrite(5, TimeUnit.MINUTES)
.build(test2 -> this.testRepo.find2(test2));
// How do I add to cache manager, and specify a name?
推荐答案
是可以的.由于您需要微调每个缓存,因此您可能最好自己定义它们.回到您的示例,下一步将是:
Yes it is possible. Since you need to fine tune every cache, you are probably better at defining them yourself. Back to your example, the next step would be:
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
new CaffeineCache("first", loadingCache1),
new CaffeineCache("second", loadingCache2)));
然后您可以照常使用它,例如
And then you can use that as usual, e.g.
@Cacheable("first")
public Foo load(String id) { ... }
如果您使用的是Spring Boot,则可以将单个缓存公开为bean(因此是org.springframework.cache.Cache
实现),我们将对其进行检测并为您自动创建SimpleCacheManager
.
If you are using Spring Boot, you can just expose the individual cache as beans (so org.springframework.cache.Cache
implementations) and we'll detect them and create a SimpleCacheManager
automatically for you.
请注意,此策略允许您将缓存抽象用于不同的实现. first
可能是咖啡因缓存,而second
可能是来自另一个提供程序的缓存.
Note that this strategy allows you to use the cache abstraction with different implementations. first
could be a caffeine cache and second
a cache from another provider.
这篇关于Spring CaffeineCacheManager中添加了多个Caffeine LoadingCaches的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!