使用自定义 DiskSpaceHealthIndicator(Spring Boot Actuator)?

Using a custom DiskSpaceHealthIndicator (Spring Boot Actuator)?

我的springapplication.yaml:

management:
  ...
  endpoint:
    health:
      show-details: ALWAYS
    info:
      enabled: false
  health:
    diskspace:
      path: "some-path"
      threshold: 536870912

这将使用 https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.html 执行健康检查。

我想 extend/wrap org.springframework.boot.actuate.system.DiskSpaceHealthIndicator 添加一些特定于应用程序的行为。有没有办法将我的应用程序配置为使用我自己的自定义版本,例如com.acme.myapp.CustomDiskSpaceHealthIndicator 而不是 org.springframework.boot.actuate.system.DiskSpaceHealthIndicator?

是的,您可以简单地提供一个名为 diskSpaceHealthIndicator 的自定义 bean,它将替换默认的 DiskSpaceHealthIndicator:

@Configuration
public class DiskSpaceHealthIndicatorConfiguration {

    @Bean
    public DiskSpaceHealthIndicator diskSpaceHealthIndicator(DiskSpaceHealthIndicatorProperties properties) {
        return new MyDiskSpaceHealthIndicator(properties.getPath(), properties.getThreshold());
    }

    private static class MyDiskSpaceHealthIndicator extends DiskSpaceHealthIndicator {

        public MyDiskSpaceHealthIndicator(File path, DataSize threshold) {
            super(path, threshold);
        }

        @Override
        protected void doHealthCheck(Builder builder) throws Exception {
            // Do whatever you need here
            super.doHealthCheck(builder);
            builder.withDetail("custom details", "whatever");
        }
    }
}