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