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

作者:梦想画家 时间:2022-06-12 14:54:59 

健康检查是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(关闭)通信。如果任一服务宕机,应用程序将被视为宕机。因此,我们将写入两个运行状况指标。


@Component
public class ServiceAHealthIndicator implements HealthIndicator {
   private final String message_key = "Service A";
   @Override
   public Health health() {
       if (!isRunningServiceA()) {
           return Health.down().withDetail(message_key, "Not Available").build();
       }
       return Health.up().withDetail(message_key, "Available").build();
   }
   private Boolean isRunningServiceA() {
       Boolean isRunning = true;
       // Logic Skipped
       return isRunning;
   }
}

@Component
public class ServiceBHealthIndicator implements HealthIndicator {
   private final String message_key = "Service B";
   @Override
   public Health health() {
       if (!isRunningServiceB()) {
           return Health.down().withDetail(message_key, "Not Available").build();
       }
       return Health.up().withDetail(message_key, "Available").build();
   }
   private Boolean isRunningServiceB() {
       Boolean isRunning = false;
       // Logic Skipped
       return isRunning;
   }
}

现在,我们看到健康监控响应中增加的指标。ServerA状态是UP,ServiceB是DOWN,因此整个监控检测状态为DOWN.


{
 "status": "DOWN",
 "components": {
   "diskSpace": {
     "status": "UP",
     "details": {
       "total": 214748360704,
       "free": 112483229696,
       "threshold": 10485760,
       "exists": true
     }
   },
   "ping": {
     "status": "UP"
   },
   "serviceA": {
     "status": "UP",
     "details": {
       "Service A": "Available"
     }
   },
   "serviceB": {
     "status": "DOWN",
     "details": {
       "Service B": "Not Available"
     }
   }
 }
}

3.2 自定义组合健康检查

前面示例很容易查看各个指标各自的状态。但有时需要基于几个指标查看资源的状态,则需要使用 HealthContributor ,该接口没有定义方法,仅用于标记。如果一个服务有另外两个动作组合进行实现,只有两者同时工作该服务状态才算正常。最后使用 CompositeHealthContributors组合多个指标:


public class ServiceAHealthIndicator
   implements HealthIndicator, HealthContributor {
...
}

下面定义组合健康检查指标:


@Component("UserServiceAPI")
public class UserServiceAPIHealthContributor
   implements CompositeHealthContributor {

private Map<String, HealthContributor>
         contributors = new LinkedHashMap<>();
 @Autowired
 public UserServiceAPIHealthContributor(
     ServiceAHealthIndicator serviceAHealthIndicator, ServiceBHealthIndicator serviceBHealthIndicator) {

contributors.put("serverA",  serviceAHealthIndicator);
   contributors.put("serverB", serviceBHealthIndicator);
 }
 /**
  *  return list of health contributors
  */
 @Override
 public Iterator<NamedContributor<HealthContributor>> iterator() {
   return contributors.entrySet().stream()
      .map((entry) -> NamedContributor.of(entry.getKey(), entry.getValue())).iterator();
 }

@Override
 public HealthContributor getContributor(String name) {
   return contributors.get(name);
 }
}

现在我们使用serverA和serverB组合新的检查UserServiceAPI。

4. 总结

本文我们学习了Spring Boot健康指标及相关配置、以及预定义的健康指标,同时介绍了如何自定义健康指标。

来源:https://blog.csdn.net/neweastsun/article/details/108933365

标签:Spring,Boot,Actuator,健康检查
0
投稿

猜你喜欢

  • springcloud eureka切换nacos的配置方法

    2022-05-19 01:58:47
  • SpringBoot中@ConfigurationProperties注解实现配置绑定的三种方法

    2023-03-19 12:36:25
  • Java 信号量Semaphore的实现

    2023-06-19 11:00:34
  • Java实现聊天室界面

    2023-12-15 10:43:32
  • Java多线程之Park和Unpark原理

    2023-03-29 15:46:11
  • Java判断两个日期相差天数的方法

    2021-11-29 05:55:07
  • springboot使用mybatis一对多的关联查询问题记录

    2023-05-25 14:31:03
  • Java实现五子棋游戏的完整代码

    2022-07-01 15:32:34
  • JAVA实现KMP算法理论和示例代码

    2021-08-06 07:13:44
  • MyBatis 中 ${}和 #{}的正确使用方法(千万不要乱用)

    2023-11-29 05:02:37
  • Java 中ThreadLocal类详解

    2022-01-31 19:58:17
  • Java对象类型的判断详解

    2023-07-26 09:55:07
  • 解读Spring-boot的debug调试

    2022-06-09 15:04:06
  • SpringBoot配置SwaggerUI访问404错误的解决方法

    2021-10-02 19:33:56
  • Java操作redis设置第二天凌晨过期的解决方案

    2022-11-15 11:40:10
  • Spring @Conditional注解原理解析

    2022-10-04 16:09:51
  • Java中两个List之间的比较方法(差集、交集和并集)

    2023-03-06 06:34:42
  • c#实现多线程局域网聊天系统

    2022-12-01 23:34:25
  • C#获取真实IP地址实现方法

    2022-01-05 11:35:49
  • java数据库唯一id生成工具类

    2023-04-04 22:53:34
  • asp之家 软件编程 m.aspxhome.com