Skip to main content
 首页 » 编程设计

Spring Boot Actuator自定义健康检查

2022年07月19日131Free-Thinker

Spring Boot Actuator自定义健康检查

健康检查是Spring Boot Actuator中重要端点之一,可以非常容易查看应用运行至状态。本文在前文的基础上介绍如何自定义健康检查。

1. 概述

本节我们简单说明下依赖及启用配置,展示缺省健康信息。首先需要引入依赖:

 compile("org.springframework.boot:spring-boot-starter-actuator") 

现在通过http://localhost:8080/actuator/health端点进行验证:

{"status":"UP"} 

缺省该端点返回应用中很多组件的汇总健康信息,但可以修改属性配置展示详细内容:

management: 
  endpoint: 
    health: 
      show-details: always 

现在再次访问返回结果如下:

{ 
  "status": "UP", 
  "components": { 
    "diskSpace": { 
      "status": "UP", 
      "details": { 
        "total": 214748360704, 
        "free": 112483500032, 
        "threshold": 10485760, 
        "exists": true 
      } 
    }, 
    "ping": { 
      "status": "UP" 
    } 
  } 
} 

查看DiskSpaceHealthIndicatorProperties文件的源码:

@ConfigurationProperties(prefix = "management.health.diskspace") 
public class DiskSpaceHealthIndicatorProperties { 
 
	/** 
	 * Path used to compute the available disk space. 
	 */ 
	private File path = new File("."); 
 
	/** 
	 * Minimum disk space that should be available. 
	 */ 
	private DataSize threshold = DataSize.ofMegabytes(10); 
 
	public File getPath() { 
		return this.path; 
	} 
 
	public void setPath(File path) { 
		this.path = path; 
	} 
 
	public DataSize getThreshold() { 
		return this.threshold; 
	} 
 
	public void setThreshold(DataSize threshold) { 
		Assert.isTrue(!threshold.isNegative(), "threshold must be greater than or equal to 0"); 
		this.threshold = threshold; 
	} 
} 

上面结果显示当前项目启动的路径 . ,报警值 为10M ,这些属性都可以通过配置进行修改。

2. 预定义健康指标

上面Json响应显示“ping”和“diskSpace”检查。这些检查也称为健康指标,如果应用引用了数据源,Spring会增加db健康指标;同时“diskSpace”是缺省配置。

Spring Boot包括很多预定义的健康指标,下面列出其中一部分:

  • DataSourceHealthIndicator
  • MongoHealthIndicator
  • Neo4jHealthIndicator
  • CassandraHealthIndicator
  • RedisHealthIndicator
  • CassandraHealthIndicator
  • RabbitHealthIndicator
  • CouchbaseHealthIndicator
  • DiskSpaceHealthIndicator (见上面示例)
  • ElasticsearchHealthIndicator
  • InfluxDbHealthIndicator
  • JmsHealthIndicator
  • MailHealthIndicator
  • SolrHealthIndicator

如果在Spring Boot应用中使用Mongo或Solr等,则Spring Boot会自动增加相应健康指标。

3. 自定义健康指标

Spring Boot提供了一捆预定义健康指标,但并没有阻止你增加自己的健康指标。一般有两种自定义类型检查:
单个健康指标组件和组合健康指标组件。

3.1 自定义单个指标组件

自定义需要实现HealthIndicator接口并重新health()方法,同时增加@Component注解。假设示例应用程序与服务A(启动)和服务B(关闭)通信。如果任一服务宕机,应用程序将被视为宕机。因此,我们将写入两个运行状况指标。

@Component 
public class ServiceAHealthIndicator implements HealthIndicator { 
    private final String message_key = "Service A"; 
    @Override 
    public Health health() { 
        if (!isRunningServiceA()) { 
            return Health.down().withDetail(message_key, "Not Available").build(); 
        } 
        return Health.up().withDetail(message_key, "Available").build(); 
    } 
 
    private Boolean isRunningServiceA() { 
        Boolean isRunning = true; 
        // Logic Skipped 
 
        return isRunning; 
    } 
} 
@Component 
public class ServiceBHealthIndicator implements HealthIndicator { 
    private final String message_key = "Service B"; 
 
    @Override 
    public Health health() { 
        if (!isRunningServiceB()) { 
            return Health.down().withDetail(message_key, "Not Available").build(); 
        } 
 
        return Health.up().withDetail(message_key, "Available").build(); 
    } 
 
    private Boolean isRunningServiceB() { 
        Boolean isRunning = false; 
        // Logic Skipped 
 
        return isRunning; 
    } 
} 

现在,我们看到健康监控响应中增加的指标。ServerA状态是UP,ServiceB是DOWN,因此整个监控检测状态为DOWN.

{ 
  "status": "DOWN", 
  "components": { 
    "diskSpace": { 
      "status": "UP", 
      "details": { 
        "total": 214748360704, 
        "free": 112483229696, 
        "threshold": 10485760, 
        "exists": true 
      } 
    }, 
    "ping": { 
      "status": "UP" 
    }, 
    "serviceA": { 
      "status": "UP", 
      "details": { 
        "Service A": "Available" 
      } 
    }, 
    "serviceB": { 
      "status": "DOWN", 
      "details": { 
        "Service B": "Not Available" 
      } 
    } 
  } 
} 

3.2 自定义组合健康检查

前面示例很容易查看各个指标各自的状态。但有时需要基于几个指标查看资源的状态,则需要使用 HealthContributor ,该接口没有定义方法,仅用于标记。如果一个服务有另外两个动作组合进行实现,只有两者同时工作该服务状态才算正常。最后使用 CompositeHealthContributors组合多个指标:

public class ServiceAHealthIndicator  
    implements HealthIndicator, HealthContributor { 
... 
} 

下面定义组合健康检查指标:

@Component("UserServiceAPI") 
public class UserServiceAPIHealthContributor  
    implements CompositeHealthContributor { 
   
  private Map<String, HealthContributor>  
          contributors = new LinkedHashMap<>(); 
 
  @Autowired 
  public UserServiceAPIHealthContributor( 
      ServiceAHealthIndicator serviceAHealthIndicator, ServiceBHealthIndicator serviceBHealthIndicator) { 
   
    contributors.put("serverA",  serviceAHealthIndicator); 
    contributors.put("serverB", serviceBHealthIndicator); 
  } 
 
  /** 
   *  return list of health contributors 
   */ 
  @Override 
  public Iterator<NamedContributor<HealthContributor>> iterator() { 
    return contributors.entrySet().stream() 
       .map((entry) -> NamedContributor.of(entry.getKey(), entry.getValue())).iterator(); 
  } 
   
  @Override 
  public HealthContributor getContributor(String name) { 
    return contributors.get(name); 
  } 
} 

现在我们使用serverA和serverB组合新的检查UserServiceAPI。

4. 总结

本文我们学习了Spring Boot健康指标及相关配置、以及预定义的健康指标,同时介绍了如何自定义健康指标。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/108933365