欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot健康检查实现原理

程序员文章站 2023-11-22 15:23:46
相信看完之前文章的同学都知道了SpringBoot自动装配的套路了,直接看 文件,当我们使用的时候只需要引入如下依赖 然后在 包下去就可以找到这个文件 自动装配 查看这个文件发现引入了很多的配置类,这里先关注一下 系列的类,这里咱们拿第一个 为例来解析一下。看名字就知道这个是RabbitMQ的健康检 ......

相信看完之前文章的同学都知道了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);
    }
}

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

  1. @conditionalonxxx系列又出现了,前两个就是说如果当前存在rabbittemplate这个bean也就是说我们的项目中使用到了rabbitmq才能进行下去
  2. @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类的自动配置才能继续下去

  1. @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个beanapplicationhealthindicatororderedhealthaggregator
这两个bean的作用稍后再说,现在回到rabbithealthindicatorautoconfiguration

  1. @autoconfigureafter这个对整体逻辑没影响,暂且不提
  2. 类中注册了一个beanhealthindicator这个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);
        }
    }

}
  1. 首先这里注入了一个对象healthaggregator,这个对象就是刚才注册的orderedhealthaggregator
  2. 第一个createhealthindicator方法执行逻辑为:如果传入的beans的size 为1,则调用createhealthindicator创建healthindicator
    否则创建compositehealthindicator,遍历传入的beans,依次创建healthindicator,加入到compositehealthindicator
  3. 第二个createhealthindicator的执行逻辑为:获得compositehealthindicatorconfiguration中的泛型参数根据泛型参数h对应的class和s对应的class,在h对应的class中找到声明了参数为s类型的构造器进行实例化
  4. 最后这里创建出来的bean为rabbithealthindicator
  5. 回忆起之前学习健康检查的使用时,如果我们需要自定义健康检查项时一般的操作都是实现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的
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的健康检查实现原理全部解析完成