SpringBoot健康检查实现原理
相信看完之前文章的同学都知道了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个beanapplicationhealthindicator
和orderedhealthaggregator
这两个bean的作用稍后再说,现在回到rabbithealthindicatorautoconfiguration
类
-
@autoconfigureafter
这个对整体逻辑没影响,暂且不提 - 类中注册了一个bean
healthindicator
这个bean的创建逻辑是在父类中的
public 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
这个类
@configuration class 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的
然后都放入了其中一个聚合的实现类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的健康检查实现原理全部解析完成
下一篇: Flash cs3怎么制作声音按钮元件?