Health 資訊是從 ApplicationContext 中所有的 HealthIndicator 的 Bean 中收集的, Spring Boot 內建了一些 HealthIndicator。
部落格地址:blog.720ui.com/
內建 HealthIndicator 監控檢測
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. |
我們,來看下原始碼清單。
可見,Spring Boot 幫忙我們整合了許多比較常見的健康監控,例如 MySQL、 MongoDB、 Redis、 ElasticSearch、 Solr、 RabbitMQ 等。
自定義 HealthIndicator 監控檢測
一般情況下,Spring Boot 提供的健康監控無法滿足我們複雜的業務場景,此時,我們就需要定製自己的 HealthIndicator, 擴充套件自己的業務監控。
我們,實現 HealthIndicator 介面建立一個簡單的檢測器類。它的作用很簡單,只是進行服務狀態監測。此時,通過重寫 health() 方法來實現健康檢查。
@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();
}
}複製程式碼
我們,來看看列印結果。
{
"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 方法即可。
一般情況下,我們不會直接實現 HealthIndicator 介面,而是繼承 AbstractHealthIndicator 抽象類。因為,我們只需要重寫 doHealthCheck 方法,並在這個方法中我們關注於具體的健康檢測的業務邏輯服務。
我們,來看看列印結果。
{
"status": "UP",
"cusDiskSpace": {
"status": "UP",
"disk.free": 79479193600,
"disk.total": 104856547328
}
}複製程式碼
原始碼
相關示例完整程式碼: springboot-action
(完)
更多精彩文章,盡在「服務端思維」微信公眾號!