电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

詳解SpringBoot健康檢查的實現原理

瀏覽:34日期:2023-03-21 13:15:37

SpringBoot自動裝配的套路,直接看 spring.factories 文件,當我們使用的時候只需要引入如下依賴

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>

然后在 org.springframework.boot.spring-boot-actuator-autoconfigure 包下去就可以找到這個文件

自動裝配

查看這個文件發現引入了很多的配置類,這里先關注一下 XXXHealthIndicatorAutoConfiguration 系列的類,這里咱們拿第一個 RabbitHealthIndicatorAutoConfiguration 為例來解析一下。看名字就知道這個是RabbitMQ的健康檢查的自動配置類

@Configuration@ConditionalOnClass(RabbitTemplate.class)@ConditionalOnBean(RabbitTemplate.class)@ConditionalOnEnabledHealthIndicator('rabbit')@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)@AutoConfigureAfter(RabbitAutoConfiguration.class)public class RabbitHealthIndicatorAutoConfiguration extends CompositeHealthIndicatorConfiguration<RabbitHealthIndicator, RabbitTemplate> { private final Map<String, RabbitTemplate> rabbitTemplates; public RabbitHealthIndicatorAutoConfiguration( Map<String, RabbitTemplate> rabbitTemplates) { this.rabbitTemplates = rabbitTemplates; } @Bean @ConditionalOnMissingBean(name = 'rabbitHealthIndicator') public HealthIndicator rabbitHealthIndicator() { return createHealthIndicator(this.rabbitTemplates); }}

按照以往的慣例,先解析注解

@ConditionalOnXXX 系列又出現了,前兩個就是說如果當前存在 RabbitTemplate 這個bean也就是說我們的項目中使用到了RabbitMQ才能進行下去 @ConditionalOnEnabledHealthIndicator 這個注解很明顯是SpringBoot actuator自定義的注解,看一下吧

@Conditional(OnEnabledHealthIndicatorCondition.class)public @interface ConditionalOnEnabledHealthIndicator { String value();}class OnEnabledHealthIndicatorCondition extends OnEndpointElementCondition { OnEnabledHealthIndicatorCondition() { super('management.health.', ConditionalOnEnabledHealthIndicator.class); }}public abstract class OnEndpointElementCondition extends SpringBootCondition { private final String prefix; private final Class<? extends Annotation> annotationType; protected OnEndpointElementCondition(String prefix, Class<? extends Annotation> annotationType) { this.prefix = prefix; this.annotationType = annotationType; } @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); String endpointName = annotationAttributes.getString('value'); ConditionOutcome outcome = getEndpointOutcome(context, endpointName); if (outcome != null) { return outcome; } return getDefaultEndpointsOutcome(context); } protected ConditionOutcome getEndpointOutcome(ConditionContext context, String endpointName) { Environment environment = context.getEnvironment(); String enabledProperty = this.prefix + endpointName + '.enabled'; if (environment.containsProperty(enabledProperty)) { boolean match = environment.getProperty(enabledProperty, Boolean.class, true); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType).because( this.prefix + endpointName + '.enabled is ' + match)); } return null; } protected ConditionOutcome getDefaultEndpointsOutcome(ConditionContext context) { boolean match = Boolean.valueOf(context.getEnvironment() .getProperty(this.prefix + 'defaults.enabled', 'true')); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType).because( this.prefix + 'defaults.enabled is considered ' + match)); }}public abstract class SpringBootCondition implements Condition { private final Log logger = LogFactory.getLog(getClass()); @Override public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String classOrMethodName = getClassOrMethodName(metadata); try { ConditionOutcome outcome = getMatchOutcome(context, metadata); logOutcome(classOrMethodName, outcome); recordEvaluation(context, classOrMethodName, outcome); return outcome.isMatch(); } catch (NoClassDefFoundError ex) { throw new IllegalStateException( 'Could not evaluate condition on ' + classOrMethodName + ' due to ' + ex.getMessage() + ' not ' + 'found. Make sure your own configuration does not rely on ' + 'that class. This can also happen if you are ' + '@ComponentScanning a springframework package (e.g. if you ' + 'put a @ComponentScan in the default package by mistake)', ex); } catch (RuntimeException ex) { throw new IllegalStateException( 'Error processing condition on ' + getName(metadata), ex); } } private void recordEvaluation(ConditionContext context, String classOrMethodName, ConditionOutcome outcome) { if (context.getBeanFactory() != null) { ConditionEvaluationReport.get(context.getBeanFactory()) .recordConditionEvaluation(classOrMethodName, this, outcome); } }}

上方的入口方法是 SpringBootCondition 類的 matches 方法, getMatchOutcome 這個方法則是子類 OnEndpointElementCondition 的,這個方法首先會去環境變量中查找是否存在 management.health.rabbit.enabled 屬性,如果沒有的話則去查找 management.health.defaults.enabled 屬性,如果這個屬性還沒有的話則設置默認值為true

當這里返回true時整個 RabbitHealthIndicatorAutoConfiguration 類的自動配置才能繼續下去

@AutoConfigureBefore 既然這樣那就先看看類 HealthIndicatorAutoConfiguration 都是干了啥再回來吧

@Configuration@EnableConfigurationProperties({ HealthIndicatorProperties.class })public class HealthIndicatorAutoConfiguration { private final HealthIndicatorProperties properties; public HealthIndicatorAutoConfiguration(HealthIndicatorProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean({ HealthIndicator.class, ReactiveHealthIndicator.class }) public ApplicationHealthIndicator applicationHealthIndicator() { return new ApplicationHealthIndicator(); } @Bean @ConditionalOnMissingBean(HealthAggregator.class) public OrderedHealthAggregator healthAggregator() { OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator(); if (this.properties.getOrder() != null) { healthAggregator.setStatusOrder(this.properties.getOrder()); } return healthAggregator; }}

首先這個類引入了配置文件 HealthIndicatorProperties 這個配置類是系統狀態相關的配置

@ConfigurationProperties(prefix = 'management.health.status')public class HealthIndicatorProperties { private List<String> order = null; private final Map<String, Integer> httpMapping = new HashMap<>();}

接著就是注冊了2個bean ApplicationHealthIndicator 和 OrderedHealthAggregator 這兩個bean的作用稍后再說,現在回到 RabbitHealthIndicatorAutoConfiguration 類

@AutoConfigureAfterHealthIndicatorpublic abstract class CompositeHealthIndicatorConfiguration<H extends HealthIndicator, S> { @Autowired private HealthAggregator healthAggregator; protected HealthIndicator createHealthIndicator(Map<String, S> beans) { if (beans.size() == 1) { return createHealthIndicator(beans.values().iterator().next()); } CompositeHealthIndicator composite = new CompositeHealthIndicator( this.healthAggregator); for (Map.Entry<String, S> entry : beans.entrySet()) { composite.addHealthIndicator(entry.getKey(), createHealthIndicator(entry.getValue())); } return composite; } @SuppressWarnings('unchecked') protected H createHealthIndicator(S source) { Class<?>[] generics = ResolvableType .forClass(CompositeHealthIndicatorConfiguration.class, getClass()) .resolveGenerics(); Class<H> indicatorClass = (Class<H>) generics[0]; Class<S> sourceClass = (Class<S>) generics[1]; try { return indicatorClass.getConstructor(sourceClass).newInstance(source); } catch (Exception ex) { throw new IllegalStateException('Unable to create indicator ' + indicatorClass + ' for source ' + sourceClass, ex); } }} 首先這里注入了一個對象 HealthAggregator ,這個對象就是剛才注冊的 OrderedHealthAggregator 第一個 createHealthIndicator 方法執行邏輯為:如果傳入的beans的size 為1,則調用 createHealthIndicator 創建 HealthIndicator 否則創建 CompositeHealthIndicator ,遍歷傳入的beans,依次創建 HealthIndicator ,加入到 CompositeHealthIndicator 中 第二個 createHealthIndicator 的執行邏輯為:獲得 CompositeHealthIndicatorConfiguration 中的泛型參數根據泛型參數H對應的class和S對應的class,在H對應的class中找到聲明了參數為S類型的構造器進行實例化 最后這里創建出來的bean為 RabbitHealthIndicator 回憶起之前學習健康檢查的使用時,如果我們需要自定義健康檢查項時一般的操作都是實現 HealthIndicator 接口,由此可以猜測 RabbitHealthIndicator 應該也是這樣做的。觀察這個類的繼承關系可以發現這個類繼承了一個實現實現此接口的類 AbstractHealthIndicator ,而RabbitMQ的監控檢查流程則如下代碼所示

//這個方法是AbstractHealthIndicator的public 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(); }//下方兩個方法是由類RabbitHealthIndicator實現的protected void doHealthCheck(Health.Builder builder) throws Exception { builder.up().withDetail('version', getVersion()); } private String getVersion() { return this.rabbitTemplate.execute((channel) -> channel.getConnection() .getServerProperties().get('version').toString()); }健康檢查

上方一系列的操作之后,其實就是搞出了一個RabbitMQ的 HealthIndicator 實現類,而負責檢查RabbitMQ健康不健康也是這個類來負責的。由此我們可以想象到如果當前環境存在MySQL、Redis、ES等情況應該也是這么個操作

那么接下來無非就是當有調用方訪問如下地址時,分別調用整個系統的所有的 HealthIndicator 的實現類的 health 方法即可了

http://ip:port/actuator/health

HealthEndpointAutoConfiguration

上邊說的這個操作過程就在類 HealthEndpointAutoConfiguration 中,這個配置類同樣也是在 spring.factories 文件中引入的

@Configuration@EnableConfigurationProperties({HealthEndpointProperties.class, HealthIndicatorProperties.class})@AutoConfigureAfter({HealthIndicatorAutoConfiguration.class})@Import({HealthEndpointConfiguration.class, HealthEndpointWebExtensionConfiguration.class})public class HealthEndpointAutoConfiguration { public HealthEndpointAutoConfiguration() { }}

這里重點的地方在于引入的 HealthEndpointConfiguration 這個類

@Configurationclass HealthEndpointConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint public HealthEndpoint healthEndpoint(ApplicationContext applicationContext) { return new HealthEndpoint(HealthIndicatorBeansComposite.get(applicationContext)); }}

這個類只是構建了一個類 HealthEndpoint ,這個類我們可以理解為一個SpringMVC的Controller,也就是處理如下請求的

http://ip:port/actuator/health

那么首先看一下它的構造方法傳入的是個啥對象吧

public static HealthIndicator get(ApplicationContext applicationContext) { HealthAggregator healthAggregator = getHealthAggregator(applicationContext); Map<String, HealthIndicator> indicators = new LinkedHashMap<>(); indicators.putAll(applicationContext.getBeansOfType(HealthIndicator.class)); if (ClassUtils.isPresent('reactor.core.publisher.Flux', null)) { new ReactiveHealthIndicators().get(applicationContext) .forEach(indicators::putIfAbsent); } CompositeHealthIndicatorFactory factory = new CompositeHealthIndicatorFactory(); return factory.createHealthIndicator(healthAggregator, indicators); }

跟我們想象中的一樣,就是通過Spring容器獲取所有的 HealthIndicator 接口的實現類,我這里只有幾個默認的和RabbitMQ

詳解SpringBoot健康檢查的實現原理

然后都放入了其中一個聚合的實現類 CompositeHealthIndicator 中

既然 HealthEndpoint構建好了,那么只剩下最后一步處理請求了

@Endpoint(id = 'health')public class HealthEndpoint { private final HealthIndicator healthIndicator; @ReadOperation public Health health() { return this.healthIndicator.health(); }}

剛剛我們知道,這個類是通過 CompositeHealthIndicator 構建的,所以 health 方法的實現就在這個類中

public Health health() { Map<String, Health> healths = new LinkedHashMap<>(); for (Map.Entry<String, HealthIndicator> entry : this.indicators.entrySet()) { //循環調用 healths.put(entry.getKey(), entry.getValue().health()); } //對結果集排序 return this.healthAggregator.aggregate(healths); }

至此SpringBoot的健康檢查實現原理全部解析完成

以上就是詳解SpringBoot健康檢查的實現原理的詳細內容,更多關于SpringBoot健康檢查實現原理的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
主站蜘蛛池模板: 定制防伪标签_防伪标签印刷_防伪标签厂家-510品保防伪网 | 京马网,京马建站,网站定制,营销型网站建设,东莞建站,东莞网站建设-首页-京马网 | 桁架楼承板-钢筋桁架楼承板-江苏众力达钢筋楼承板厂 | 塑胶地板-商用PVC地板-pvc地板革-安耐宝pvc塑胶地板厂家 | 爆炸冲击传感器-无线遥测传感器-航天星百科 | 全自动定氮仪-半自动凯氏定氮仪厂家-祎鸿仪器 | 小型气象站_车载气象站_便携气象站-山东风途物联网 | 蓝莓施肥机,智能施肥机,自动施肥机,水肥一体化项目,水肥一体机厂家,小型施肥机,圣大节水,滴灌施工方案,山东圣大节水科技有限公司官网17864474793 | 焊管生产线_焊管机组_轧辊模具_焊管设备_焊管设备厂家_石家庄翔昱机械 | 防火板_饰面耐火板价格、厂家_品牌认准格林雅 | 水性绝缘漆_凡立水_绝缘漆树脂_环保绝缘漆-深圳维特利环保材料有限公司 | 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 在线浊度仪_悬浮物污泥浓度计_超声波泥位计_污泥界面仪_泥水界面仪-无锡蓝拓仪表科技有限公司 | 锂离子电池厂家-山东中信迪生电源 | 整车VOC采样环境舱-甲醛VOC预处理舱-多舱法VOC检测环境仓-上海科绿特科技仪器有限公司 | 上海小程序开发-小程序制作-上海小程序定制开发公司-微信商城小程序-上海咏熠 | 压力变送器-上海武锐自动化设备有限公司 | 水稻烘干机,小麦烘干机,大豆烘干机,玉米烘干机,粮食烘干机_巩义市锦华粮食烘干机械制造有限公司 水环真空泵厂家,2bv真空泵,2be真空泵-淄博真空设备厂 | 自动螺旋上料机厂家价格-斗式提升机定制-螺杆绞龙输送机-杰凯上料机 | 宏源科技-房地产售楼系统|线上开盘系统|售楼管理系统|线上开盘软件 | 制氮设备_PSA制氮机_激光切割制氮机_氮气机生产厂家-苏州西斯气体设备有限公司 | 天津暖气片厂家_钢制散热器_天津铜铝复合暖气片_维尼罗散热器 | 包塑软管|金属软管|包塑金属软管-闵彬管业 | 蒜肠网-动漫,二次元,COSPLAY,漫展以及收藏型模型,手办,玩具的新媒体.(原变形金刚变迷TF圈) | 科普仪器菏泽市教育教学仪器总厂| 定制奶茶纸杯_定制豆浆杯_广东纸杯厂_[绿保佳]一家专业生产纸杯碗的厂家 | Magnescale探规,Magnescale磁栅尺,Magnescale传感器,Magnescale测厚仪,Mitutoyo光栅尺,笔式位移传感器-苏州连达精密量仪有限公司 | 沈阳缠绕膜价格_沈阳拉伸膜厂家_沈阳缠绕膜厂家直销 | 游泳池设备安装工程_恒温泳池设备_儿童游泳池设备厂家_游泳池水处理设备-东莞市君达泳池设备有限公司 | 砂尘试验箱_淋雨试验房_冰水冲击试验箱_IPX9K淋雨试验箱_广州岳信试验设备有限公司 | 浴室柜-浴室镜厂家-YINAISI · 意大利设计师品牌 | 咿耐斯 |-浙江台州市丰源卫浴有限公司 | 超声波清洗机_大型超声波清洗机_工业超声波清洗设备-洁盟清洗设备 | 越南专线物流_东莞国际物流_东南亚专线物流_行通物流 | 无刷电机_直流无刷电机_行星减速机-佛山市藤尺机电设备有限公司 无菌检查集菌仪,微生物限度仪器-苏州长留仪器百科 | 西装定制/做厂家/公司_西装订做/制价格/费用-北京圣达信西装 | 电磁铁_小型推拉电磁铁_电磁阀厂家-深圳市宗泰电机有限公司 | 煤矿支护网片_矿用勾花菱形网_缝管式_管缝式锚杆-邯郸市永年区志涛工矿配件有限公司 | 智慧食堂_食堂管理系统_食堂订餐_食堂消费系统—客易捷 | 洁净化验室净化工程_成都实验室装修设计施工_四川华锐净化公司 | 电缆接头-防爆电缆接头-格兰头-金属电缆接头-防爆填料函 | 温州富欧金属封头-不锈钢封头厂家|