在 Spring Actuator (CacheManager) 中注册 Caffeine Cache [英] Register Caffeine Cache in Spring Actuator (CacheManager)
问题描述
我们正在使用 Spring Boot 2 和 Spring Actuator.创建如下缓存时:
We're using Spring Boot 2 and Spring Actuator. When creating a cache like the following:
@Bean
public CaffeineCache someCache() {
return new CaffeineCache("my-cache",
Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.SECONDS)
.build());
}
它注册到 Spring Actuator 中,可以通过端点访问和处理:
it is registered into Spring Actuator and can be accessed and handle via endpoints:
❯ http GET localhost:8080/actuator/caches
{
"cacheManagers": {
"cacheManager": {
"caches": {
"my-cache": {
"target": "com.github.benmanes.caffeine.cache.BoundedLocalCache$BoundedLocalManualCache"
}
}
}
}
}
但是,这在使用注释 @Cacheable
时有效 - 但我想创建一个缓存并将其用作地图.
However, this is valid when using the annotation @Cacheable
- but I would like to create a cache and use it as a map.
因此,我可以创建:
@Bean
public com.github.benmanes.caffeine.cache.Cache<String, MyObject> customCache(QueryServiceProperties config) {
return Caffeine.newBuilder()
.maximumSize(10)
.expireAfterAccess(10, TimeUnit.SECONDS)
.build();
}
它可以工作,但不能被 Spring Actuator 发现.有没有办法注册这种缓存?
And it works but it cannot be discovered by Spring Actuator. Is there any way to register this kind of cache?
推荐答案
改编自这个 Answer 我做了以下事情:>
Addapted from this Answer I did the following:
@Autowired
private CacheMetricsRegistrar cacheMetricsRegistrar;
private LoadingCache<Key, MyObject> cache;
@PostConstruct
public void init() {
cache = Caffeine.newBuilder()
.maximumSize(10_000)
.refreshAfterWrite(cacheDuration)
.recordStats()
.build(this::loadMyObject);
// trick the compiler
Cache tmp = cache;
cacheMetricsRegistrar.bindCacheToRegistry(new CaffeineCache(CACHE_NAME, tmp), Tag.of("name", CACHE_NAME));
}
缓存现在应该显示在缓存执行器端点中,例如"http://localhost:8080/metrics/cache.gets"
The Cache should now show up in the cache actuator endpoints, e.g. "http://localhost:8080/metrics/cache.gets"
这篇关于在 Spring Actuator (CacheManager) 中注册 Caffeine Cache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!