How to make the `@Endpoint(id = “health”)` working in Spring Boot 2.0?

后端 未结 2 1862
你的背包
你的背包 2021-01-18 03:21

I have tried the new way of customizing the health Actuator in Spring Boot 2.0.0.M5, as described here: https://spring.io/blog/2017/08/22/introducing-actuator-endpoints-in-s

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 03:36

    Provide your own @WebEndpoint like

    @Component
    @WebEndpoint(id = "acmehealth")
    public class AcmeHealthEndpoint {
    
        @ReadOperation
        public String hello() {
          return "hello health";
        }
    }
    

    and

    1. include it
    2. map the original /health to, say, /internal/health
    3. map your custom endpoint to /health

    via application.properties:

    management.endpoints.web.exposure.include=acmehealth
    management.endpoints.web.path-mapping.health=internal/health
    management.endpoints.web.path-mapping.acmehealth=/health
    

    This will override /health completely, not just add the information to the existing /health, as a custom HealthIndicator would. Question is, what you want, because @Endpoint(id = "health") and "My intention is not to create a custom actuator myhealth, but to customize the existing health actuator" kind of collide. But you can use the existing HealthEndpoint in your AcmeHealthEndpoint and accomplish both:

    @Component
    @WebEndpoint(id = "prettyhealth")
    public class PrettyHealthEndpoint {
    
        private final HealthEndpoint healthEndpoint;
        private final ObjectMapper objectMapper;
    
        @Autowired
        public PrettyHealthEndpoint(HealthEndpoint healthEndpoint, ObjectMapper objectMapper) {
            this.healthEndpoint = healthEndpoint;
            this.objectMapper = objectMapper;
        }
    
        @ReadOperation(produces = "application/json")
        public String getHealthJson() throws JsonProcessingException {
            Health health = healthEndpoint.health();
            ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
            return writer.writeValueAsString(health);
        }
    
        @ReadOperation
        public String prettyHealth() throws JsonProcessingException {
            return "
    " + getHealthJson() + "
    "; } }

提交回复
热议问题