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

DemoApplication.java

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

HelloController.java

@RestController
public class HelloController {
    private final HelloService helloService;

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

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

HelloService.java

@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に数回アクセスした後で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

参考