Spring BootでRedis Cacheのmetricsを収集する

Spring Boot 2.4からRedis Cacheのmetricsが収集できるようになったので試してみた。

ソースコード

build.gradle

plugins {
    id 'org.springframework.boot' version '2.4.1'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'io.micrometer:micrometer-registry-prometheus'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

Java

@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@RestController
public class HelloController {
    private final HelloService helloService;

    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @GetMapping("/hello")
    public String hello() {
        return helloService.hello();
    }
}

@Service
public class HelloService {
    @Cacheable(cacheNames = "cache1")
    public String hello() {
        return "Hello!";
    }
}

application.yml

Redisはデフォルトのlocalhost:6379を使う。

spring:
  cache:
    cache-names: cache1
    redis:
      enable-statistics: true
management:
  endpoints:
    web:
      exposure:
        include: prometheus

動作確認

/helloに数回アクセスした後にSpring Boot Actuatorのprometheusのendpointを参照すると、cacheのhitやmissなどのmetricsが確認できる。

http://localhost:8080/actuator/prometheus

# HELP cache_puts_total The number of entries added to the cache
# TYPE cache_puts_total counter
cache_puts_total{cache="cache1",cacheManager="cacheManager",name="cache1",} 1.0
# 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="cache1",cacheManager="cacheManager",name="cache1",result="miss",} 1.0
cache_gets_total{cache="cache1",cacheManager="cacheManager",name="cache1",result="pending",} 0.0
cache_gets_total{cache="cache1",cacheManager="cacheManager",name="cache1",result="hit",} 6.0

参考

https://github.com/spring-projects/spring-boot/issues/22701
https://github.com/spring-projects/spring-data-redis/issues/961
https://docs.spring.io/spring-boot/docs/2.4.1/reference/html/production-ready-features.html#production-ready-metrics-cache