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原理及其使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/layuan110/article/details/110001630
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/751785

相关文章

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

Python使用FFmpeg实现高效音频格式转换工具

《Python使用FFmpeg实现高效音频格式转换工具》在数字音频处理领域,音频格式转换是一项基础但至关重要的功能,本文主要为大家介绍了Python如何使用FFmpeg实现强大功能的图形化音频转换工具... 目录概述功能详解软件效果展示主界面布局转换过程截图完成提示开发步骤详解1. 环境准备2. 项目功能结

SpringBoot使用ffmpeg实现视频压缩

《SpringBoot使用ffmpeg实现视频压缩》FFmpeg是一个开源的跨平台多媒体处理工具集,用于录制,转换,编辑和流式传输音频和视频,本文将使用ffmpeg实现视频压缩功能,有需要的可以参考... 目录核心功能1.格式转换2.编解码3.音视频处理4.流媒体支持5.滤镜(Filter)安装配置linu

Redis中的Lettuce使用详解

《Redis中的Lettuce使用详解》Lettuce是一个高级的、线程安全的Redis客户端,用于与Redis数据库交互,Lettuce是一个功能强大、使用方便的Redis客户端,适用于各种规模的J... 目录简介特点连接池连接池特点连接池管理连接池优势连接池配置参数监控常用监控工具通过JMX监控通过Pr

apache的commons-pool2原理与使用实践记录

《apache的commons-pool2原理与使用实践记录》ApacheCommonsPool2是一个高效的对象池化框架,通过复用昂贵资源(如数据库连接、线程、网络连接)优化系统性能,这篇文章主... 目录一、核心原理与组件二、使用步骤详解(以数据库连接池为例)三、高级配置与优化四、典型应用场景五、注意事

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

使用Python实现Windows系统垃圾清理

《使用Python实现Windows系统垃圾清理》Windows自带的磁盘清理工具功能有限,无法深度清理各类垃圾文件,所以本文为大家介绍了如何使用Python+PyQt5开发一个Windows系统垃圾... 目录一、开发背景与工具概述1.1 为什么需要专业清理工具1.2 工具设计理念二、工具核心功能解析2.

Linux系统之stress-ng测压工具的使用

《Linux系统之stress-ng测压工具的使用》:本文主要介绍Linux系统之stress-ng测压工具的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、理论1.stress工具简介与安装2.语法及参数3.具体安装二、实验1.运行8 cpu, 4 fo

Java使用MethodHandle来替代反射,提高性能问题

《Java使用MethodHandle来替代反射,提高性能问题》:本文主要介绍Java使用MethodHandle来替代反射,提高性能问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录一、认识MethodHandle1、简介2、使用方式3、与反射的区别二、示例1、基本使用2、(重要)

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元