Register Caffeine Cache in Spring Actuator (CacheManager)

一个人想着一个人 提交于 2021-02-18 18:59:54

问题


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

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"
                }
            }
        }
    }
}

However, this is valid when using the annotation @Cacheable - but I would like to create a cache and use it as a map.

Therefore, I can create:

    @Bean
    public com.github.benmanes.caffeine.cache.Cache<String, MyObject> customCache(QueryServiceProperties config) {
        return Caffeine.newBuilder()
                .maximumSize(10)
                .expireAfterAccess(10, TimeUnit.SECONDS)
                .build();
    }

And it works but it cannot be discovered by Spring Actuator. Is there any way to register this kind of cache?


回答1:


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

The Cache should now show up in the cache actuator endpoints, e.g. "http://localhost:8080/metrics/cache.gets"



来源:https://stackoverflow.com/questions/56158365/register-caffeine-cache-in-spring-actuator-cachemanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!