0

I'm using Caffeine cache for Java Spring Boot com.github.ben-manes.caffeine:caffeine:3.1.1. This is my cache configuration class:

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

I also have test methods with Cacheable annotation like this:

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

and finally I have a test controller which populates cache:

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

However, when I check Spring actuator metrics I only see one cache-related metric: size

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

However, why don't I see other metrics like cache.gets, cache.puts etc. as should be provided by Micrometer?

hitchhiker
  • 1,099
  • 5
  • 19
  • 44

1 Answers1

1

The metrics you are seeing are the common CacheManger metrics. To get Caffeine specific ones, you'll need to monitor those caches as they are created.

I've not run this code, but subclassing the CaffeineCacheManager and hooking into the createNativeCaffeineCache should do the trick:

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

There is likely a better way. But this should work.

checketts
  • 14,167
  • 10
  • 53
  • 82