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

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程