1. private final Map rabbitTemplates; 什么时候注入的
  2. 对应的health的controller是在哪里处理的,看完SpringMVC中去寻找关系

相信看完之前文章的同学都知道了SpringBoot自动装配的套路了,直接看spring.factories文件,当我们使用的时候只需要引入如下依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>

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

自动装配

XXXHealthIndicatorAutoConfiguration

查看这个文件发现引入了很多的配置类,这里先关注一下XXXHealthIndicatorAutoConfiguration系列的类,这里咱们拿第一个RabbitHealthIndicatorAutoConfiguration为例来解析一下。看名字就知道这个是RabbitMQ的健康检查的自动配置类

  1. @Configuration
  2. @ConditionalOnClass(RabbitTemplate.class)
  3. @ConditionalOnBean(RabbitTemplate.class)
  4. @ConditionalOnEnabledHealthIndicator("rabbit")
  5. @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
  6. @AutoConfigureAfter(RabbitAutoConfiguration.class)
  7. public class RabbitHealthIndicatorAutoConfiguration extends
  8. CompositeHealthIndicatorConfiguration<RabbitHealthIndicator, RabbitTemplate> {
  9. private final Map<String, RabbitTemplate> rabbitTemplates;
  10. public RabbitHealthIndicatorAutoConfiguration(
  11. Map<String, RabbitTemplate> rabbitTemplates) {
  12. this.rabbitTemplates = rabbitTemplates;
  13. }
  14. @Bean
  15. @ConditionalOnMissingBean(name = "rabbitHealthIndicator")
  16. public HealthIndicator rabbitHealthIndicator() {
  17. return createHealthIndicator(this.rabbitTemplates);
  18. }
  19. }

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

  1. @ConditionalOnXXX系列又出现了,前两个就是说如果当前存在RabbitTemplate这个bean也就是说我们的项目中使用到了RabbitMQ才能进行下去
  2. @ConditionalOnEnabledHealthIndicator这个注解很明显是SpringBoot actuator自定义的注解,看一下吧
  1. @Conditional(OnEnabledHealthIndicatorCondition.class)
  2. public @interface ConditionalOnEnabledHealthIndicator {
  3. String value();
  4. }
  5. class OnEnabledHealthIndicatorCondition extends OnEndpointElementCondition {
  6. OnEnabledHealthIndicatorCondition() {
  7. super("management.health.", ConditionalOnEnabledHealthIndicator.class);
  8. }
  9. }
  10. public abstract class OnEndpointElementCondition extends SpringBootCondition {
  11. private final String prefix;
  12. private final Class<? extends Annotation> annotationType;
  13. protected OnEndpointElementCondition(String prefix,
  14. Class<? extends Annotation> annotationType) {
  15. this.prefix = prefix;
  16. this.annotationType = annotationType;
  17. }
  18. @Override
  19. public ConditionOutcome getMatchOutcome(ConditionContext context,
  20. AnnotatedTypeMetadata metadata) {
  21. AnnotationAttributes annotationAttributes = AnnotationAttributes
  22. .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName()));
  23. String endpointName = annotationAttributes.getString("value");
  24. ConditionOutcome outcome = getEndpointOutcome(context, endpointName);
  25. if (outcome != null) {
  26. return outcome;
  27. }
  28. return getDefaultEndpointsOutcome(context);
  29. }
  30. protected ConditionOutcome getEndpointOutcome(ConditionContext context,
  31. String endpointName) {
  32. Environment environment = context.getEnvironment();
  33. String enabledProperty = this.prefix + endpointName + ".enabled";
  34. if (environment.containsProperty(enabledProperty)) {
  35. boolean match = environment.getProperty(enabledProperty, Boolean.class, true);
  36. return new ConditionOutcome(match,
  37. ConditionMessage.forCondition(this.annotationType).because(
  38. this.prefix + endpointName + ".enabled is " + match));
  39. }
  40. return null;
  41. }
  42. protected ConditionOutcome getDefaultEndpointsOutcome(ConditionContext context) {
  43. boolean match = Boolean.valueOf(context.getEnvironment()
  44. .getProperty(this.prefix + "defaults.enabled", "true"));
  45. return new ConditionOutcome(match,
  46. ConditionMessage.forCondition(this.annotationType).because(
  47. this.prefix + "defaults.enabled is considered " + match));
  48. }
  49. }
  50. public abstract class SpringBootCondition implements Condition {
  51. private final Log logger = LogFactory.getLog(getClass());
  52. @Override
  53. public final boolean matches(ConditionContext context,
  54. AnnotatedTypeMetadata metadata) {
  55. String classOrMethodName = getClassOrMethodName(metadata);
  56. try {
  57. ConditionOutcome outcome = getMatchOutcome(context, metadata);
  58. logOutcome(classOrMethodName, outcome);
  59. recordEvaluation(context, classOrMethodName, outcome);
  60. return outcome.isMatch();
  61. }
  62. catch (NoClassDefFoundError ex) {
  63. throw new IllegalStateException(
  64. "Could not evaluate condition on " + classOrMethodName + " due to "
  65. + ex.getMessage() + " not "
  66. + "found. Make sure your own configuration does not rely on "
  67. + "that class. This can also happen if you are "
  68. + "@ComponentScanning a springframework package (e.g. if you "
  69. + "put a @ComponentScan in the default package by mistake)",
  70. ex);
  71. }
  72. catch (RuntimeException ex) {
  73. throw new IllegalStateException(
  74. "Error processing condition on " + getName(metadata), ex);
  75. }
  76. }
  77. private void recordEvaluation(ConditionContext context, String classOrMethodName,
  78. ConditionOutcome outcome) {
  79. if (context.getBeanFactory() != null) {
  80. ConditionEvaluationReport.get(context.getBeanFactory())
  81. .recordConditionEvaluation(classOrMethodName, this, outcome);
  82. }
  83. }
  84. }

上方的入口方法是SpringBootCondition类的matches方法,getMatchOutcome 这个方法则是子类OnEndpointElementCondition的,这个方法首先会去环境变量中查找是否存在management.health.rabbit.enabled属性,如果没有的话则去查找management.health.defaults.enabled属性,如果这个属性还没有的话则设置默认值为true

当这里返回true时整个RabbitHealthIndicatorAutoConfiguration类的自动配置才能继续下去

  1. @AutoConfigureBefore既然这样那就先看看类HealthIndicatorAutoConfiguration都是干了啥再回来吧
  1. @Configuration
  2. @EnableConfigurationProperties({ HealthIndicatorProperties.class })
  3. public class HealthIndicatorAutoConfiguration {
  4. private final HealthIndicatorProperties properties;
  5. public HealthIndicatorAutoConfiguration(HealthIndicatorProperties properties) {
  6. this.properties = properties;
  7. }
  8. @Bean
  9. @ConditionalOnMissingBean({ HealthIndicator.class, ReactiveHealthIndicator.class })
  10. public ApplicationHealthIndicator applicationHealthIndicator() {
  11. return new ApplicationHealthIndicator();
  12. }
  13. @Bean
  14. @ConditionalOnMissingBean(HealthAggregator.class)
  15. public OrderedHealthAggregator healthAggregator() {
  16. OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator();
  17. if (this.properties.getOrder() != null) {
  18. healthAggregator.setStatusOrder(this.properties.getOrder());
  19. }
  20. return healthAggregator;
  21. }
  22. }

HealthIndicatorProperties

首先这个类引入了配置文件HealthIndicatorProperties这个配置类是系统状态相关的配置

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

接着就是注册了2个beanApplicationHealthIndicatorOrderedHealthAggregator 这两个bean的作用稍后再说,现在回到RabbitHealthIndicatorAutoConfiguration

  1. @AutoConfigureAfter这个对整体逻辑没影响,暂且不提
  2. 类中注册了一个beanHealthIndicator这个bean的创建逻辑是在父类中的
  1. public abstract class CompositeHealthIndicatorConfiguration<H extends HealthIndicator, S> {
  2. @Autowired
  3. private HealthAggregator healthAggregator;
  4. protected HealthIndicator createHealthIndicator(Map<String, S> beans) {
  5. if (beans.size() == 1) {
  6. return createHealthIndicator(beans.values().iterator().next());
  7. }
  8. CompositeHealthIndicator composite = new CompositeHealthIndicator(
  9. this.healthAggregator);
  10. for (Map.Entry<String, S> entry : beans.entrySet()) {
  11. composite.addHealthIndicator(entry.getKey(),
  12. createHealthIndicator(entry.getValue()));
  13. }
  14. return composite;
  15. }
  16. @SuppressWarnings("unchecked")
  17. protected H createHealthIndicator(S source) {
  18. Class<?>[] generics = ResolvableType
  19. .forClass(CompositeHealthIndicatorConfiguration.class, getClass())
  20. .resolveGenerics();
  21. Class<H> indicatorClass = (Class<H>) generics[0];
  22. Class<S> sourceClass = (Class<S>) generics[1];
  23. try {
  24. return indicatorClass.getConstructor(sourceClass).newInstance(source);
  25. }
  26. catch (Exception ex) {
  27. throw new IllegalStateException("Unable to create indicator " + indicatorClass
  28. + " for source " + sourceClass, ex);
  29. }
  30. }
  31. }
  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

  1. //这个方法是AbstractHealthIndicator的
  2. public final Health health() {
  3. Health.Builder builder = new Health.Builder();
  4. try {
  5. doHealthCheck(builder);
  6. }
  7. catch (Exception ex) {
  8. if (this.logger.isWarnEnabled()) {
  9. String message = this.healthCheckFailedMessage.apply(ex);
  10. this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE,
  11. ex);
  12. }
  13. builder.down(ex);
  14. }
  15. return builder.build();
  16. }
  17. //下方两个方法是由类RabbitHealthIndicator实现的
  18. protected void doHealthCheck(Health.Builder builder) throws Exception {
  19. builder.up().withDetail("version", getVersion());
  20. }
  21. private String getVersion() {
  22. return this.rabbitTemplate.execute((channel) -> channel.getConnection()
  23. .getServerProperties().get("version").toString());
  24. }

健康检查

上方一系列的操作之后,其实就是搞出了一个RabbitMQ的HealthIndicator实现类,而负责检查RabbitMQ健康不健康也是这个类来负责的。由此我们可以想象到如果当前环境存在MySQL、Redis、ES等情况应该也是这么个操作

那么接下来无非就是当有调用方访问如下地址时,分别调用整个系统的所有的HealthIndicator的实现类的health方法即可了

  1. http://ip:port/actuator/health

HealthEndpointAutoConfiguration

上边说的这个操作过程就在类HealthEndpointAutoConfiguration中,这个配置类同样也是在spring.factories文件中引入的

  1. @Configuration
  2. @EnableConfigurationProperties({HealthEndpointProperties.class, HealthIndicatorProperties.class})
  3. @AutoConfigureAfter({HealthIndicatorAutoConfiguration.class})
  4. @Import({HealthEndpointConfiguration.class, HealthEndpointWebExtensionConfiguration.class})
  5. public class HealthEndpointAutoConfiguration {
  6. public HealthEndpointAutoConfiguration() {
  7. }
  8. }

HealthEndpointConfiguration

这里重点的地方在于引入的HealthEndpointConfiguration这个类

  1. @Configuration
  2. class HealthEndpointConfiguration {
  3. @Bean
  4. @ConditionalOnMissingBean
  5. @ConditionalOnEnabledEndpoint
  6. public HealthEndpoint healthEndpoint(ApplicationContext applicationContext) {
  7. return new HealthEndpoint(HealthIndicatorBeansComposite.get(applicationContext));
  8. }
  9. }

这个类只是构建了一个类HealthEndpoint,这个类我们可以理解为一个SpringMVC的Controller,也就是处理如下请求的

  1. http://ip:port/actuator/health

那么首先看一下它的构造方法传入的是个啥对象吧

  1. public static HealthIndicator get(ApplicationContext applicationContext) {
  2. HealthAggregator healthAggregator = getHealthAggregator(applicationContext);
  3. Map<String, HealthIndicator> indicators = new LinkedHashMap<>();
  4. indicators.putAll(applicationContext.getBeansOfType(HealthIndicator.class));
  5. if (ClassUtils.isPresent("reactor.core.publisher.Flux", null)) {
  6. new ReactiveHealthIndicators().get(applicationContext)
  7. .forEach(indicators::putIfAbsent);
  8. }
  9. CompositeHealthIndicatorFactory factory = new CompositeHealthIndicatorFactory();
  10. return factory.createHealthIndicator(healthAggregator, indicators);
  11. }

跟我们想象中的一样,就是通过Spring容器获取所有的HealthIndicator接口的实现类,我这里只有几个默认的和RabbitMQ

然后都放入了其中一个聚合的实现类CompositeHealthIndicator

既然HealthEndpoint构建好了,那么只剩下最后一步处理请求了

  1. @Endpoint(id = "health")
  2. public class HealthEndpoint {
  3. private final HealthIndicator healthIndicator;
  4. @ReadOperation
  5. public Health health() {
  6. return this.healthIndicator.health();
  7. }
  8. }

CompositeHealthIndicator

刚刚我们知道,这个类是通过CompositeHealthIndicator构建的,所以health方法的实现就在这个类中

  1. public Health health() {
  2. Map<String, Health> healths = new LinkedHashMap<>();
  3. for (Map.Entry<String, HealthIndicator> entry : this.indicators.entrySet()) {
  4. //循环调用
  5. healths.put(entry.getKey(), entry.getValue().health());
  6. }
  7. //对结果集排序
  8. return this.healthAggregator.aggregate(healths);
  9. }

至此SpringBoot的健康检查实现原理全部解析完成