skip to Main Content

I have a Spring Boot 2 application that has caching with Caffeine cache manager already implemented. Caching is implemented in a standard way with @Cacheable, @CacheEvict, @CachePut annotations.

I migrated the app for using Redis to have caching distributed between pods.

The problem now is with metrics. Before migration Caffeine exposed cache metrics like cache_puts_total, cache_gets_total, etc. and now there is nothing. Is there something implemented for metrics in RedisCacheManager? I can not find anything.

2

Answers


  1. Unfortunately as you can see in the Spring Boot documentation: 52. Metrics, Spring Boot does not provide cache statistics for Redis by default:

    By default, Spring Boot provides cache statistics for EhCache, Hazelcast, Infinispan, JCache and Guava. You can add additional CacheStatisticsProvider beans if your favourite caching library isn’t supported out of the box.

    As another alternative to implementing this yourself, you can use Redisson. This Redis client comes with an integration with Spring that exposes Prometheus metrics. Your metrics will look just like you hint:

    # HELP cache_gets_total the number of times cache lookup methods have returned an uncached (newly loaded) value, or null
    # TYPE cache_gets_total counter
    cache_gets_total{cache="...",cacheManager="...",name="...",result="miss",} 0.0
    cache_gets_total{cache="...",cacheManager="...",name="...",result="hit",} 0.0
    
    # HELP cache_puts_total The number of entries added to the cache
    # TYPE cache_puts_total counter
    cache_puts_total{cache="...",cacheManager="...",name="...",} 0.0
    
    Login or Signup to reply.
  2. You can configure the RedisCacheManager to give the metrics to you. First, you need to implement the CacheStatisticsCollector by adding the necessary types of metrics from the Prometheus. Then this implementation should be added to the RedisCacheWriter, which should be placed in the RedisCacheManager. For instance:

    RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .prefixCacheNameWith("prefix:")
                .disableCachingNullValues();
    RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory)
                .withStatisticsCollector(new PrometheusCollector());
    RedisCacheManager redisCacheManager =  RedisCacheManager.builder()
                .cacheWriter(cacheWriter)
                .cacheDefaults(configuration.entryTtl(Duration.ofHours(1)))
                .build();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search