spring-boot-actuator-Health原理

news/2025/11/4 16:07:18/文章来源:https://www.cnblogs.com/LQBlog/p/19190594

说明

在容器化部署下,如何判断服务是否健康通过 curl  127.0.0.1:8080/actuator/health检查 是否是健康状态

使用示例以sentinel为例

实现抽象类

public class SentinelHealthIndicator extends AbstractHealthIndicator {private DefaultListableBeanFactory beanFactory;private SentinelProperties sentinelProperties;public SentinelHealthIndicator(DefaultListableBeanFactory beanFactory,SentinelProperties sentinelProperties) {this.beanFactory = beanFactory;this.sentinelProperties = sentinelProperties;}@Overrideprotected void doHealthCheck(Health.Builder builder) throws Exception {Map<String, Object> detailMap = new HashMap<>();// If sentinel isn't enabled, set the status up and set the enabled to false in// detailif (!sentinelProperties.isEnabled()) {detailMap.put("enabled", false);builder.up().withDetails(detailMap);return;}detailMap.put("enabled", true);// Check health of Dashboardboolean dashboardUp = true;List<Tuple2<String, Integer>> consoleServerList = TransportConfig.getConsoleServerList();if (CollectionUtils.isEmpty(consoleServerList)) {// If Dashboard isn't configured, it's OK and mark the status of Dashboard// with UNKNOWN.detailMap.put("dashboard",new Status(Status.UNKNOWN.getCode(), "dashboard isn't configured"));}else {// If Dashboard is configured, send a heartbeat message to it and check the// resultHeartbeatSender heartbeatSender = HeartbeatSenderProvider.getHeartbeatSender();boolean result = heartbeatSender.sendHeartbeat();if (result) {detailMap.put("dashboard", Status.UP);}else {// If failed to send heartbeat message, means that the Dashboard is DOWNdashboardUp = false;detailMap.put("dashboard",new Status(Status.UNKNOWN.getCode(), String.format("the dashboard servers [%s] one of them can't be connected",consoleServerList)));}}// Check health of DataSourceboolean dataSourceUp = true;Map<String, Object> dataSourceDetailMap = new HashMap<>();detailMap.put("dataSource", dataSourceDetailMap);// Get all DataSources and each call loadConfig to check if it's OK// If no Exception thrown, it's OK// Note:// Even if the dynamic config center is down, the loadConfig() might return// successfully// e.g. for Nacos client, it might retrieve from the local cache)// But in most circumstances it's okayMap<String, AbstractDataSource> dataSourceMap = beanFactory.getBeansOfType(AbstractDataSource.class);for (Map.Entry<String, AbstractDataSource> dataSourceMapEntry : dataSourceMap.entrySet()) {String dataSourceBeanName = dataSourceMapEntry.getKey();AbstractDataSource dataSource = dataSourceMapEntry.getValue();try {dataSource.loadConfig();dataSourceDetailMap.put(dataSourceBeanName, Status.UP);}catch (Exception e) {// If one DataSource failed to loadConfig, means that the DataSource is// DOWNdataSourceUp = false;dataSourceDetailMap.put(dataSourceBeanName,new Status(Status.UNKNOWN.getCode(), e.getMessage()));}}// If Dashboard and DataSource are both OK, the health status is UPif (dashboardUp && dataSourceUp) {builder.up().withDetails(detailMap);}else {builder.unknown().withDetails(detailMap);}}}
View Code

注入容器

        @Bean@ConditionalOnMissingBean@ConditionalOnEnabledHealthIndicator("sentinel") //management.health.sentinel.enabled=false 可禁用public SentinelHealthIndicator sentinelHealthIndicator(DefaultListableBeanFactory beanFactory,SentinelProperties sentinelProperties) {return new SentinelHealthIndicator(beanFactory, sentinelProperties);}

访问CURL端点

image

 初始化原理

1、初始化HealthIndicatorRegistry

org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorAutoConfiguration#healthIndicatorRegistry

 @Bean@ConditionalOnMissingBean({HealthIndicatorRegistry.class})public HealthIndicatorRegistry healthIndicatorRegistry(ApplicationContext applicationContext) {//内部会从容器获取HealthIndicator实现类 里面就有我们的sentinel实现类return HealthIndicatorRegistryBeans.get(applicationContext);}

 

2、org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorRegistryBeans#get

    public static HealthIndicatorRegistry get(ApplicationContext applicationContext) {Map<String, HealthIndicator> indicators = new LinkedHashMap();//从容器获取indicators.putAll(applicationContext.getBeansOfType(HealthIndicator.class));if (ClassUtils.isPresent("reactor.core.publisher.Flux", (ClassLoader)null)) {(new ReactiveHealthIndicators()).get(applicationContext).forEach(indicators::putIfAbsent);}HealthIndicatorRegistryFactory factory = new HealthIndicatorRegistryFactory();//构建 HealthIndicatorRegistryreturn factory.createHealthIndicatorRegistry(indicators);}

3、返回含有所有health健康检查的 registry

     public HealthIndicatorRegistry createHealthIndicatorRegistry(Map<String, HealthIndicator> healthIndicators) {Assert.notNull(healthIndicators, "HealthIndicators must not be null");//初始化return initialize(new DefaultHealthIndicatorRegistry(), healthIndicators);}protected <T extends HealthIndicatorRegistry> T initialize(T registry,Map<String, HealthIndicator> healthIndicators) {for (Map.Entry<String, HealthIndicator> entry : healthIndicators.entrySet()) {//这里主要是获取bean的名字 截取掉 如 sentinelHealthIndicator  截取掉HealthIndicator  name为sentinelString name = this.healthIndicatorNameFactory.apply(entry.getKey());registry.register(name, entry.getValue());}return registry;}

执行原理

1、actor模式会在Spring MVC注册一个mappring入口为

org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.OperationHandler#handle

->

org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.ServletWebOperationAdapter#handle

->

org.springframework.boot.actuate.endpoint.annotation.AbstractDiscoveredOperation#invoke

->

org.springframework.boot.actuate.health.HealthEndpointWebExtension#health

->

org.springframework.boot.actuate.health.HealthEndpointWebExtension#health

     @ReadOperationpublic WebEndpointResponse<Health> health(SecurityContext securityContext) {//内部就是从 初始化的registry遍历所有的处理器获取检查结果return this.responseMapper.map(this.delegate.health(), securityContext);}

2、org.springframework.boot.actuate.health.HealthEndpoint#health

image

 3、org.springframework.boot.actuate.health.CompositeHealthIndicator#health

    @Overridepublic Health health() {Map<String, Health> healths = new LinkedHashMap<>();for (Map.Entry<String, HealthIndicator> entry : this.registry.getAll().entrySet()) {//遍历执行 获取结果
            healths.put(entry.getKey(), entry.getValue().health());}//进行聚合返回return this.aggregator.aggregate(healths);}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/955794.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2025年广州防霉检测机构权威推荐榜单:除螨检测/除臭效果测试/输配水设备检测源头机构精选

防霉检测市场正迎来质量与技术双重升级,据行业数据显示,2025年中国防霉检测市场规模预计突破15亿元,年增长率稳定在12% 以上。 在消费品质量与安全要求日益提高的背景下,防霉检测已成为家居、建材、纺织、电子电器…

2025年钣金机箱外壳加工厂家权威推荐榜单:钣金壳体/变频器钣金壳体/钣金加工壳体源头厂家精选

在工业制造智能化转型的推动下,钣金机箱外壳加工作为装备制造的基础环节,市场需求持续增长。据2025年行业统计数据显示,中国钣金加工市场规模已突破4200亿元,年均增长率保持在12%以上。 随着新能源、通信、自动化等…

从零到一:我的开源AI商业化实战之路

今天我想分享使用三种主流开源方案实现商业变现的真实经历,希望能为正在探索AI商业化的你提供一些参考。从零到一:我的开源AI商业化实战之路 缘起:技术人的迷思 曾经,我也坚信"技术越厉害,赚钱越容易"。…

机器学习 BASEML到底是什么

from .base import baseml from .BaseClassification import Classification from .BaseRegression import Regression from .BaseCluster import Cluster from .BaseDimentionReduction import DimentionReduction__a…

体育馆游泳卡押金原路退回,安心无忧—东方仙盟 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

DesignSpark Mechanical (DSM)输入用户名密码提示在注册过程中发生错误

前言全局说明输入用户名密码提示“注册过程中发生错误”一、说明 1.1 环境: Windows 11 家庭版 24H2 26100.4061 Designspark Mechanical 6.0.3二、问题 一直可以用 DSM 都很正常,最近换了电脑,需要登录,输入用户名…

字段(辨析:字段、对象、属性和方法在 JavaScript 中的关系)

1. 对象 (Object) :名词,实体,是一个具体的实体,它是属性和方法的集合。它就是一个“东西”。 2. 属性 (Property) :形容词,状态,是描述对象状态或特征的值。它回答的是对象“是什么”或“有什么”的问题。属性…

P14364 [CSP-S 2025] 员工招聘 / employ 笔记

考完这次 CSP 真正的感受到了自己的弱小,「努力」了大半年,面对正赛题解还是跟读天书一样,什么都看不懂,文化课成绩倒是步步低降了。 我该在哪里停留?我问我自己。设最终的排列是 \(p_{1\dots n}\),\([1,i)\) 拒…

Spring boot 使用虚拟线程示例

项目使用版本Spring Boot v3.5.6 jdk 25配置 创建 VirtualThreadConfig 配置类 @Configuration @EnableAsync public class VirtualThreadConfig {@Bean(name = "virtualThreadExecutor")public TaskExecuto…

微算法科技(NASDAQ MLGO):以隐私计算区块链筑牢多方安全计算(MPC)安全防线

在数据价值日益凸显的当下,数据的流通与融合成为释放其潜力的关键。多方安全计算(MPC)作为隐私计算的核心技术,使参与方能够在不泄露原始数据的情况下协同完成计算任务,为数据的跨主体合作利用提供了可能。然而,…

怎么把idea的目录结构,以文本形式输出?——idea使用tree

1.在 idea 中的 Terminal 终端输入:tree或者tree -f如果想要保存到文件,例如保存到 C 盘tree >> C:/codeTree.txtwidown 系統下tree /f >> C:/codeTree.txt参数说明:-a 显示所有文件和目录。 -A 使用A…

2025年11月沼气直燃厂家综合评测:徐州海德测控技术有限公司领跑

2025年11月沼气直燃厂家综合评测:徐州海德测控技术有限公司领跑 文章摘要 本文深入分析2025年沼气直燃设备市场格局,对行业前十品牌进行全方位评测。徐州海德测控技术有限公司凭借卓越的技术实力、严格的质量管控体系…

微信小程序初始配置

1、设置AppSecret,将AppID、AppSecret配置到代码验证用2、配置服务器域名3、设置业务域名、需要在站点底下文件验证

python爬虫scrapy框架使用 - 教程

python爬虫scrapy框架使用 - 教程pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco&q…

2025年塑烧板除尘器源头厂家权威推荐榜单:耐高温除尘器/防爆除尘器/不锈钢除尘器源头厂家精选

工业除尘领域正迎来技术升级浪潮,塑烧板除尘器因其过滤精度高、使用寿命长、维护成本低等优势,市场份额持续提升,预计2025年全球市场规模将突破50亿元。 塑烧板除尘器作为工业粉尘治理的核心设备,已广泛应用于钢铁…

2025年剪叉升降平台供应商权威推荐榜单:车载剪叉式升降平台/移动剪叉式升降平台车/轨道升降平台源头厂家精选

在工程建设与工业安装需求持续增长的背景下,一台可靠高效的剪叉升降平台已成为提升高空作业安全性与工作效率的关键装备。 剪叉升降平台作为高空作业设备中的重要类别,其稳定性与安全性直接影响着工程建设的效率与作…

第180天:横向移动篇入口切换SMB共享WMI管道DCOM组件Impacket套件CS插件

winrm&winrs&RDP横向&crackmapexec工具使用横向移动主要是基于以下三块内容 基于口令 ipc smb wi dcom winrs winrm rdp等 pth ptt ptk 基于漏洞 域控提取漏洞 Exchange漏洞攻防 基于配置 委派 dysnc asre…

利用地名来查询烟台市未来七天天气预报,在jmeter中查看响应结果

打开 JMeter,新建 “测试计划”。 2.添加线程组 右键 “测试计划” → 添加 → 线程 → 线程组。 3. 添加 HTTP 请求 右键 “线程组” → 添加 → 取样器 → HTTP 请求,配置如下: 服务器名称或 IP:API 接口的域名端…

2025 年水质测定仪厂家最新推荐榜:解析科技等企业实力剖析与选购参考养殖/便携式总磷总氮/余氯总氯/废水水质测定仪公司推荐

引言 随着环保意识提升与水质监测需求激增,水质测定仪市场规模持续扩大,但行业乱象也随之显现。部分厂家为抢占市场,推出的产品存在检测精度不达标、功能与实际需求脱节等问题,导致用户采购后无法有效开展监测工作…

2025年11月沼气直燃品牌/品牌排名前十:技术实力对比与总结

2025年11月沼气直燃品牌/品牌排名前十:技术实力对比与总结 摘要 2025年,沼气直燃行业迎来快速发展,得益于环保政策推动和新能源需求增长,市场规模预计同比增长15%以上。沼气直燃设备作为可再生能源利用的关键,高效…