Spring Boot Caffeine缓存指标仅报告缓存大小,而不报告微米命中/未命中率

2ic8powd  于 2022-12-13  发布在  Spring
关注(0)|答案(1)|浏览(196)

我正在为Java Sping Boot com.github.ben-manes.caffeine:caffeine:3.1.1使用Caffeine缓存。这是我的缓存配置类:

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class CacheConfig {
  
  @Bean
  public Caffeine<Object, Object> caffeineConfig() {
    return Caffeine.newBuilder()
        .maximumSize(10000)
        .recordStats()
        .removalListener((key, value, removalCause) -> {
          // TODO: log
        });
  }

  @Bean
  public CacheManager cacheManager(Caffeine<Object, Object> caffeine) {
    CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
    caffeineCacheManager.setCaffeine(caffeine);

    List<String> list = new ArrayList<>();
    list.add("AsyncTest.getStr");
    list.add("AsyncTest.getStr2");
    list.add("AsyncTest.getStr3");
    list.add("AsyncTest.getStr4");
    list.add("AsyncTest.getStr5");
    caffeineCacheManager.setCacheNames(list);
    return caffeineCacheManager;
  }
}

我还有一些带有Cacheable注解的测试方法,如下所示:

@Cacheable("AsyncTest.getStr")
  public String getStr(int i) {
    return "abc";
  }

最后我有一个测试控制器来填充缓存:

for (int i = 0; i < 1000; i++) {
      asyncTest.getStr(i);
    }

但是,当我检查Spring执行器指标时,我只看到一个与缓存相关的指标:大小

"myapp.cache.size": 250.0,
        "myapp.cache.size.tags": "{name=AsyncTest.getStr, cache=AsyncTest.getStr, cacheManager=cacheManager}",

但是,为什么我没有看到其他指标,如cache.getscache.puts等,而测微计应该是provided

gywdnpxw

gywdnpxw1#

您看到的指标是常见的CacheManger指标。要获得Caffeine特定的指标,您需要在创建这些缓存时对其进行monitor
我还没有运行过这段代码,但是对CaffeineCacheManager进行子类化并挂钩到createNativeCaffeineCache应该可以做到这一点:

public CacheManager cacheManager(Caffeine<Object, Object> caffeine, MeterRegistry meterRegistry) {
    CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager(){
          protected com.github.benmanes.caffeine.cache.Cache<Object, Object> createNativeCaffeineCache(String name) {
          return CaffeineCacheMetrics.monitor(meterRegistry, super.createNativeCaffeineCache(name), name);
      }

    };
    caffeineCacheManager.setCaffeine(caffeine);
}

可能有更好的方法,但这应该行得通。

相关问题