使用Spring Boot实现动态健康检查HealthChecks

import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.HealthIndicatorRegistry;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
public class App {

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

/**
 * <pre>
 * {@code 
 * curl -X PUT http://localhost:8080/healthchecks/gugu
 * curl -X PUT http://localhost:8080/healthchecks/gaga
 * 
 * curl http://localhost:8080/actuator/health
 * 
 * curl -X DELETE http://localhost:8080/healthchecks/gaga
 * }
 * </pre>
 */
@RestController
@RequestMapping("healthchecks")
@RequiredArgsConstructor
class HealthController {

    private final HealthIndicatorRegistry registry;

    @PutMapping("/{name}")
    public void addHealthCheck(@PathVariable String name) {
        registry.register(name, new DynamicHealthCheck(name));
    }

    @DeleteMapping("/{name}")
    public void removeHealthCheck(@PathVariable String name) {
        registry.unregister(name);
    }
}

@Slf4j
@RequiredArgsConstructor
class DynamicHealthCheck implements HealthIndicator {

    private final String name;

    @Override
    public Health health() {

        log.info("check health for: {}", name);

        return Health.up().build();
    }

}

application.properties

management.endpoint.health.show-details=ALWAYS

原文发布于微信公众号 - Linyb极客之路(gh_c420b2cf6b47)

原文发表时间:2018-12-13

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券