Spring boot 磁盘大小监控
在spring boot的actuator组件中有很多检查项,其中磁盘空间检查也是比较重要的一块,下面重点分析一下
1. 检查类初始化
通过注解@ConditionalOnEnabledHealthIndicator查看应用,看到有@ConditionalOnEnabledHealthIndicator(“diskspace”)内容,则为核心配置类,具体如下
@Configuration(proxyBeanMethods = false)
@ConditionalOnEnabledHealthIndicator("diskspace")
@AutoConfigureBefore(HealthContributorAutoConfiguration.class)
@EnableConfigurationProperties(DiskSpaceHealthIndicatorProperties.class)
public class DiskSpaceHealthContributorAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "diskSpaceHealthIndicator")
public DiskSpaceHealthIndicator diskSpaceHealthIndicator(DiskSpaceHealthIndicatorProperties properties) {
return new DiskSpaceHealthIndicator(properties.getPath(), properties.getThreshold());
}
}
2. 检查项配置分析
可以看到diskSpaceHealthIndicator方法中,传递了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;
}
}
可以看到主要有path和threshold属性,其中path为监控路径,默认为当前应用路径,threshold则为监控大小默认为10M,这两个属性可以通过以下两个key进行自定义指定
##检查目录
management.health.diskspace.path=/data
## 空间大小100M
management.health.diskspace.threshold=104857600
3. 核心检查方法分析
通过以上分析,对初始化已经有了初步了解,下面看一下,核心检查逻辑
public class DiskSpaceHealthIndicator extends AbstractHealthIndicator {
private static final Log logger = LogFactory.getLog(DiskSpaceHealthIndicator.class);
private final File path;
private final DataSize threshold;
/**
* Create a new {@code DiskSpaceHealthIndicator} instance.
* @param path the Path used to compute the available disk space
* @param threshold the minimum disk space that should be available
*/
public DiskSpaceHealthIndicator(File path, DataSize threshold) {
super("DiskSpace health check failed");
this.path = path;
this.threshold = threshold;
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
long diskFreeInBytes = this.path.getUsableSpace();
if (diskFreeInBytes >= this.threshold.toBytes()) {
builder.up();
}
else {
logger.warn(LogMessage.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
diskFreeInBytes, this.threshold));
builder.down();
}
builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes)
.withDetail("threshold", this.threshold.toBytes()).withDetail("exists", this.path.exists());
}
}
在请求/actuator/health接口时会调用doHealthCheck方法,此方法会获取指定目录磁盘空间大小,并与指定的最小空间做比对,如果小于最小空间,那么就会返回status为down,否则为up