spring boot health indicator原理及其使用

2024-02-27 08:20

本文主要是介绍spring boot health indicator原理及其使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

作用

sping boot health 可以通过暴露的接口来提供系统及其系统组件是否可用。默认通过/health来访问。返回结果如下:

{"status": "UP","discoveryComposite": {"description": "Spring Cloud Eureka Discovery Client","status": "UP","discoveryClient": {"description": "Spring Cloud Eureka Discovery Client","status": "UP","services": ["..."]},"eureka": {"description": "Remote status from Eureka server","status": "UP","applications": {"AOMS-MOBILE": 1,"DATA-EXCHANGE": 1,"CLOUD-GATEWAY": 2,"AOMS": 1,"AOMS-AIIS": 0,"AOMS-EUREKA": 2}}},"diskSpace": {"status": "UP","total": 313759301632,"free": 291947081728,"threshold": 10485760},"refreshScope": {"status": "UP"},"hystrix": {"status": "UP"}
}
状态说明:
  • UNKNOWN:未知状态,映射HTTP状态码为503

  • UP:正常,映射HTTP状态码为200

  • DOWN:失败,映射HTTP状态码为503

  • OUT_OF_SERVICE:不能对外提供服务,但是服务正常。映射HTTP状态码为200

    注意:UNKNOWN,DOWN,OUT_OF_SERVICE在为微服务环境下会导致注册中心中的实例也为down状态,请根据具体的业务来正确使用状态值。

自动配置的Health Indicator

自动配置的HealthIndicator主要有以下内容:

KeyNameDescription
cassandraCassandraDriverHealthIndicatorChecks that a Cassandra database is up.
couchbaseCouchbaseHealthIndicatorChecks that a Couchbase cluster is up.
datasourceDataSourceHealthIndicatorChecks that a connection to DataSource can be obtained.
diskspaceDiskSpaceHealthIndicatorChecks for low disk space.
elasticsearchElasticsearchRestHealthIndicatorChecks that an Elasticsearch cluster is up.
hazelcastHazelcastHealthIndicatorChecks that a Hazelcast server is up.
influxdbInfluxDbHealthIndicatorChecks that an InfluxDB server is up.
jmsJmsHealthIndicatorChecks that a JMS broker is up.
ldapLdapHealthIndicatorChecks that an LDAP server is up.
mailMailHealthIndicatorChecks that a mail server is up.
mongoMongoHealthIndicatorChecks that a Mongo database is up.
neo4jNeo4jHealthIndicatorChecks that a Neo4j database is up.
pingPingHealthIndicatorAlways responds with UP.
rabbitRabbitHealthIndicatorChecks that a Rabbit server is up.
redisRedisHealthIndicatorChecks that a Redis server is up.
solrSolrHealthIndicatorChecks that a Solr server is up.
分组

可以通过一个别名来启用一组指标的访问。配置的格式如下:

management.endpoint.health.group.<name>
//demo:
management.endpoint.health.group.mysys.include=db,redis,mail
management.endpoint.health.group.custom.exclude=rabbit
如何管理Health Indicator
开启

可以通过management.health.key.enabled来启用key对应的indicator。例如:

management.health.db.enabled=true
关闭
management.health.db.enabled=false
RedisHealthIndicator源码解析

下面,通过RedisHealthIndicator源码来为什么可以这么写。

代码结构

自动配置的health indicator有HealthIndicator和HealthIndicatorAutoConfiguration两部分组成。HealthIndicator所在包在org.springframework.boot.actuate

HealthIndicatorAutoConfiguration所在包在org.springframework.boot.actuate.autoconfigure
在这里插入图片描述

//RedisHealthIndicator.java
public class RedisHealthIndicator extends AbstractHealthIndicator {static final String VERSION = "version";static final String REDIS_VERSION = "redis_version";private final RedisConnectionFactory redisConnectionFactory;public RedisHealthIndicator(RedisConnectionFactory connectionFactory) {super("Redis health check failed");Assert.notNull(connectionFactory, "ConnectionFactory must not be null");this.redisConnectionFactory = connectionFactory;}@Overrideprotected void doHealthCheck(Health.Builder builder) throws Exception {RedisConnection connection = RedisConnectionUtils.getConnection(this.redisConnectionFactory);try {if (connection instanceof RedisClusterConnection) {ClusterInfo clusterInfo = ((RedisClusterConnection) connection).clusterGetClusterInfo();builder.up().withDetail("cluster_size", clusterInfo.getClusterSize()).withDetail("slots_up", clusterInfo.getSlotsOk()).withDetail("slots_fail", clusterInfo.getSlotsFail());}else {Properties info = connection.info();builder.up().withDetail(VERSION, info.getProperty(REDIS_VERSION));}}finally {RedisConnectionUtils.releaseConnection(connection,this.redisConnectionFactory);}}}
  • 主要实现doHealthCheck方法来实现具体的判断逻辑。注意,操作完成后在finally中释放资源。
  • 在父类AbstractHealthIndicator中,对doHealthCheck进行了try catch,如果出现异常,则返回Down状态。
	//AbstractHealthIndicator.java@Overridepublic final Health health() {Health.Builder builder = new Health.Builder();try {doHealthCheck(builder);}catch (Exception ex) {if (this.logger.isWarnEnabled()) {String message = this.healthCheckFailedMessage.apply(ex);this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE,ex);}builder.down(ex);}return builder.build();}

RedisHealthIndicatorAutoConfiguration完成RedisHealthIndicator的自动配置

@Configuration
@ConditionalOnClass(RedisConnectionFactory.class)
@ConditionalOnBean(RedisConnectionFactory.class)
@ConditionalOnEnabledHealthIndicator("redis")
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
@AutoConfigureAfter({ RedisAutoConfiguration.class,RedisReactiveHealthIndicatorAutoConfiguration.class })
public class RedisHealthIndicatorAutoConfiguration extendsCompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> {private final Map<String, RedisConnectionFactory> redisConnectionFactories;public RedisHealthIndicatorAutoConfiguration(Map<String, RedisConnectionFactory> redisConnectionFactories) {this.redisConnectionFactories = redisConnectionFactories;}@Bean@ConditionalOnMissingBean(name = "redisHealthIndicator")public HealthIndicator redisHealthIndicator() {return createHealthIndicator(this.redisConnectionFactories);}}
  • 重点说明ConditionalOnEnabledHealthIndicator:如果management.health..enabled为true,则生效。
  • CompositeHealthIndicatorConfiguration 中会通过HealthIndicatorRegistry注册创建的HealthIndicator
自定义Indicator
@Component
@ConditionalOnProperty(name="spring.dfs.http.send-url")
@Slf4j
public class DfsHealthIndicator implements HealthIndicator {@Value("${spring.dfs.http.send-url}")private String dsfSendUrl;@Overridepublic Health health() {log.debug("正在检查dfs配置项...");log.debug("dfs 请求地址:{}",dsfSendUrl);Health.Builder up = Health.up().withDetail("url", dsfSendUrl);try {HttpUtils.telnet(StringUtils.getIpFromUrl(dsfSendUrl),StringUtils.getPortFromUrl(dsfSendUrl));return up.build();} catch (IOException e) {e.printStackTrace();log.error("DFS配置项错误或网络超时");return up.withException(e).build();}}
}

返回值:

{"dfs": {"status": "UP","url": "10.254.131.197:8088","error": "java.net.ConnectException: Connection refused (Connection refused)"}
}

这篇关于spring boot health indicator原理及其使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/751785

相关文章

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

解决Maven项目idea找不到本地仓库jar包问题以及使用mvn install:install-file

《解决Maven项目idea找不到本地仓库jar包问题以及使用mvninstall:install-file》:本文主要介绍解决Maven项目idea找不到本地仓库jar包问题以及使用mvnin... 目录Maven项目idea找不到本地仓库jar包以及使用mvn install:install-file基

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自

Spring 请求之传递 JSON 数据的操作方法

《Spring请求之传递JSON数据的操作方法》JSON就是一种数据格式,有自己的格式和语法,使用文本表示一个对象或数组的信息,因此JSON本质是字符串,主要负责在不同的语言中数据传递和交换,这... 目录jsON 概念JSON 语法JSON 的语法JSON 的两种结构JSON 字符串和 Java 对象互转

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

JAVA保证HashMap线程安全的几种方式

《JAVA保证HashMap线程安全的几种方式》HashMap是线程不安全的,这意味着如果多个线程并发地访问和修改同一个HashMap实例,可能会导致数据不一致和其他线程安全问题,本文主要介绍了JAV... 目录1. 使用 Collections.synchronizedMap2. 使用 Concurren

Java Response返回值的最佳处理方案

《JavaResponse返回值的最佳处理方案》在开发Web应用程序时,我们经常需要通过HTTP请求从服务器获取响应数据,这些数据可以是JSON、XML、甚至是文件,本篇文章将详细解析Java中处理... 目录摘要概述核心问题:关键技术点:源码解析示例 1:使用HttpURLConnection获取Resp