Health 信息是從 ApplicationContext 中全部的 HealthIndicator 的 Bean 中收集的, Spring Boot 內置了一些 HealthIndicator。ide
Name | Description |
---|---|
CassandraHealthIndicator | Checks that a Cassandra database is up. |
DiskSpaceHealthIndicator | Checks for low disk space. |
DataSourceHealthIndicator | Checks that a connection to DataSource can be obtained. |
ElasticsearchHealthIndicator | Checks that an Elasticsearch cluster is up. |
JmsHealthIndicator | Checks that a JMS broker is up. |
MailHealthIndicator | Checks that a mail server is up. |
MongoHealthIndicator | Checks that a Mongo database is up. |
RabbitHealthIndicator | Checks that a Rabbit server is up. |
RedisHealthIndicator | Checks that a Redis server is up. |
SolrHealthIndicator | Checks that a Solr server is up. |
咱們,來看下源代碼清單。ui
可見,Spring Boot 幫忙咱們集成了許多比較常見的健康監控,例如 MySQL、 MongoDB、 Redis、 ElasticSearch、 Solr、 RabbitMQ 等。this
通常狀況下,Spring Boot 提供的健康監控沒法知足咱們複雜的業務場景,此時,咱們就須要定製本身的 HealthIndicator, 擴展本身的業務監控。spa
咱們,實現 HealthIndicator 接口建立一個簡單的檢測器類。它的做用很簡單,只是進行服務狀態監測。此時,經過重寫 health() 方法來實現健康檢查。code
@Component public class CusStatusHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); if (errorCode != 0) { return Health.down() .withDetail("status", errorCode) .withDetail("message", "服務故障") .build(); } return Health.up().build(); } private int check(){ // 對監控對象的檢測操做 return HttpStatus.NOT_FOUND.value(); } }
咱們,來看看打印結果。server
{ "status": "DOWN", "cusStatus": { "status": 404, "message": "服務故障" } }
此外,咱們還能夠經過繼承 AbstractHealthIndicator 類,建立一個檢測器類。對象
@Component public class CusDiskSpaceHealthIndicator extends AbstractHealthIndicator { private final FileStore fileStore; private final long thresholdBytes; @Autowired public CusDiskSpaceHealthIndicator( @Value("${health.filestore.path:/}") String path, @Value("${health.filestore.threshold.bytes:10485760}") long thresholdBytes) throws IOException { fileStore = Files.getFileStore(Paths.get(path)); this.thresholdBytes = thresholdBytes; } @Override protected void doHealthCheck(Health.Builder builder) throws Exception { long diskFreeInBytes = fileStore.getUnallocatedSpace(); if (diskFreeInBytes >= thresholdBytes) { builder.up(); } else { builder.down(); } long totalSpaceInBytes = fileStore.getTotalSpace(); builder.withDetail("disk.free", diskFreeInBytes); builder.withDetail("disk.total", totalSpaceInBytes); } }
AbstractHealthIndicator 實現 HealthIndicator 接口,並重寫了 health() 方法來實現健康檢查。所以,咱們只須要重寫 doHealthCheck 方法便可。blog
通常狀況下,咱們不會直接實現 HealthIndicator 接口,而是繼承 AbstractHealthIndicator 抽象類。由於,咱們只須要重寫 doHealthCheck 方法,並在這個方法中咱們關注於具體的健康檢測的業務邏輯服務。繼承
咱們,來看看打印結果。接口
{ "status": "UP", "cusDiskSpace": { "status": "UP", "disk.free": 79479193600, "disk.total": 104856547328 } }