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语言中联合体union的使用

本文编辑整理自: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=179471 一、前言 “联合体”(union)与“结构体”(struct)有一些相似之处。但两者有本质上的不同。在结构体中,各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Vim使用基础篇

本文内容大部分来自 vimtutor,自带的教程的总结。在终端输入vimtutor 即可进入教程。 先总结一下,然后再分别介绍正常模式,插入模式,和可视模式三种模式下的命令。 目录 看完以后的汇总 1.正常模式(Normal模式) 1.移动光标 2.删除 3.【:】输入符 4.撤销 5.替换 6.重复命令【. ; ,】 7.复制粘贴 8.缩进 2.插入模式 INSERT

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。