Spring Boot Actuator自定义健康检查教程

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring Boot Actuator自定义健康检查教程

jingxian   2021-07-23 我要评论
想了解Spring Boot Actuator自定义健康检查教程的相关内容吗,jingxian在本文为您仔细讲解的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring Boot,Actuator,自定义健康检查,下面大家一起来学习吧。

健康检查是Spring Boot Actuator中重要端点之一,可以非常容易查看应用运行至状态。本文在前文的基础上介绍如何自定义健康检查。

1. 概述
本节我们简单说明下依赖及启用配置,展示缺省健康信息。首先需要引入依赖:

 compile("org.springframework.boot:spring-boot-starter-actuator")

现在通过http://localhost:8080/actuator/health端点进行验证:

{"status":"UP"}

缺省该端点返回应用中很多组件的汇总健康信息,但可以修改属性配置展示详细内容:

management:
  endpoint:
    health:
      show-details: always


现在再次访问返回结果如下:

{
  "status": "UP",
  "components": {
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 214748360704,
        "free": 112483500032,
        "threshold": 10485760,
        "exists": true
      }
    },
    "ping": {
      "status": "UP"
    }
  }
}


查看DiskSpaceHealthIndicatorProperties文件的源码:

@ConfigurationProperties(prefix = "management.health.diskspace")
public class DiskSpaceHealthIndicatorProperties {

 /**
  * Path used to compute the available disk space.
  */
 private File path = new File(".");

 /**
  * Minimum disk space that should be available.
  */
 private DataSize threshold = DataSize.ofMegabytes(10);

 public File getPath() {
  return this.path;
 }

 public void setPath(File path) {
  this.path = path;
 }

 public DataSize getThreshold() {
  return this.threshold;
 }

 public void setThreshold(DataSize threshold) {
  Assert.isTrue(!threshold.isNegative(), "threshold must be greater than or equal to 0");
  this.threshold = threshold;
 }
}


上面结果显示当前项目启动的路径 . ,报警值 为10M ,这些属性都可以通过配置进行修改。

2. 预定义健康指标

上面Json响应显示“ping”和“diskSpace”检查。这些检查也称为健康指标,如果应用引用了数据源,Spring会增加db健康指标;同时“diskSpace”是缺省配置。

Spring Boot包括很多预定义的健康指标,下面列出其中一部分:

DataSourceHealthIndicator

MongoHealthIndicator

Neo4jHealthIndicator

CassandraHealthIndicator

RedisHealthIndicator

CassandraHealthIndicator

RabbitHealthIndicator

CouchbaseHealthIndicator

DiskSpaceHealthIndicator (见上面示例)

ElasticsearchHealthIndicator

InfluxDbHealthIndicator

JmsHealthIndicator

MailHealthIndicator

SolrHealthIndicator

如果在Spring Boot应用中使用Mongo或Solr等,则Spring Boot会自动增加相应健康指标。

3. 自定义健康指标

Spring Boot提供了一捆预定义健康指标,但并没有阻止你增加自己的健康指标。一般有两种自定义类型检查:

单个健康指标组件和组合健康指标组件。

3.1 自定义单个指标组件

自定义需要实现HealthIndicator接口并重新health()方法,同时增加@Component注解。假设示例应用程序与服务A(启动)和服务B(关闭)通信。如果任一服务宕机,应用程序将被视为宕机。因此,我们将写入两个运行状况指标。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们