6.SpringBoot-Actuator-健康指标Health

文章目录

  • 基础配置
  • 指标介绍
  • 自定义自己的指标
    • 简单实现
    • 返回自定义内容

基础配置

您可以使用运行状况信息来检查正在运行的应用程序的状态。
他经常用于监控软件系统,使其可以在系统出现问题时通知一些人。
运行状况端点公开的信息取决于management.endpoint.health.show-details属性
该属性可以使用以下值之一进行配置:

Name Description
never 永远不现实细节.
when-authorized 详细信息仅向授权用户显示.可以使用management.endpoint.health.roles配置授权角色.
always 向所有用户显示详细信息.

指标介绍

在合适的时候,Spring Boot会自动配置以下健康指标:

Name Description
CassandraHealthIndicator Checks that a Cassandra database is up.
CouchbaseHealthIndicator Checks that a Couchbase cluster 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.
InfluxDbHealthIndicator Checks that an InfluxDB server 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.
Neo4jHealthIndicator Checks that a Neo4j server 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.

自定义自己的指标

简单实现

    @Component
    public class MyHealthIndicator implements HealthIndicator {
        @Override
        public Health health() {
            int errorCode = check(); // perform some specific health check
            if (errorCode != 0) {
                return Health.down().withDetail("Error Code", errorCode).build();
    
            }
            return Health.up().build();
        }
        public int check(){
            return 2;
        }
    }

只要定义一个组件并实现HealthIndicator接口即可
现在访问health接口你就会发现多了一个指标

{
    "status": "DOWN",
    "details": {
        "my": {
            "status": "DOWN",
            "details": {
                "Error Code": 2
            }
        },
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 500106784768,
                "free": 385645244416,
                "threshold": 10485760
            }
        }
    }
}

返回自定义内容

我们观察返回内容会返现需要返回一个status
该状态有以下几种,每种都对应一个http状态码

status 对应http状态码 描述
DOWN 503 表示组件或子系统出现意外故障。
OUT_OF_SERVICE 503 表示组件或子系统已停止服务且不应使用
UNKNOWN 200 表示组件或子系统处于未知状态
UP 200 表示组件或子系统正在按预期运行

返回值必须是一个Health,Health本身也是一个构建器

Health.status(Status.UNKNOWN).withDetail("Error Code", errorCode).build()

通过status方法来设置状态,通过withDetail来设置返回内容详情,最后通过build方法来构建一个Health对象

你可能感兴趣的:(6.SpringBoot-Actuator-健康指标Health)