1

我们正在使用 Spring Boot 2 和 Spring Actuator。创建缓存时,如下所示:

@Bean
public CaffeineCache someCache() {
    return new CaffeineCache("my-cache",
            Caffeine.newBuilder()
                    .maximumSize(1000)
                    .expireAfterWrite(10, TimeUnit.SECONDS)
                    .build());
}

它已注册到 Spring Actuator 中,可以通过端点访问和处理:

❯ http GET localhost:8080/actuator/caches

{
    "cacheManagers": {
        "cacheManager": {
            "caches": {
                "my-cache": {
                    "target": "com.github.benmanes.caffeine.cache.BoundedLocalCache$BoundedLocalManualCache"
                }
            }
        }
    }
}

但是,这在使用注释时是有效的@Cacheable- 但我想创建一个缓存并将其用作地图。

因此,我可以创建:

    @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发现。有没有办法注册这种缓存?

4

2 回答 2

1

改编自这个答案,我做了以下事情:

@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

于 2019-07-12T12:45:43.130 回答
0

利用CacheManager

将您的自定义缓存添加到CacheManager,注入CacheManager并获取该缓存以供您使用。有关更多详细信息,请参阅https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html

于 2021-04-21T03:32:18.780 回答