在应用时,尤其是在分布式的系统中,如果系统出了问题,我们需要及时发现并解决。所以这就需要我们时时去监控应用的健康状态。
7.1.1代码实现
- 首先,我们需要引入Spring Boot Actuator的包到build.gradle文件中,如下:
implementation 'org.springframework.boot:spring-boot-starter-actuator' |
- 这个依赖使我们有能力通过节点来操作,如/env,/info,/metrics,/health等。让我们启动我们的应用,然后输入地址:http://localhost:800/health,你将会看到如下的信息:
- 在我们添加了Actuator的依赖之后,我们可以添加和执行多种监控命令。接下来,我们添加一些点位符信息到application.properties的文件中。这个文件位于src/main/resources目录下。
info.build.name=${name} |
- 接着,我们创建新的文件gradle.properties在项目的根目录下,内容如下:
version=0.0.1-SNAPSHOT |
- 在项目的根目录下的settings.gradle文件中加入rootProject.name=’BookPub’信息。
- 为了连接这些信息,我们需要修改一下build.gradle的文件,修改信息如下:
bootRun { addResources = false } processResources { filesMatching("**/application.properties") { expand(project.properties) } } |
- 启动应用,并访问http://localhost:8080/info 你将会看到如下的信息
- 让我们创建自己的健康指引器来看一下上面/health的功能是如何运行的。为了展示我们所有应用的属性状态,我们可以这样设置,如果大于或等于0,就是UP;否则就是不通宝应用是否在执行。显然,如果有错误出现,那么返回的值就会是DOWN。为了我伴着接下来的项目,我们先注释掉db-count-starter/src/main/java/org/owen/bookpubstarter/dbcount目录下的DbCountRunner.jav中的getRepsitoryName(…)方法。
- 在项目db-count-starter下的build.gradle文件中同样加入这行代码:
implementation 'org.springframework.boot:spring-boot-starter-actuator'
- 现在我们将会创建一个新的文件名称为DbCountHealthIndicator.java在db-count-starter/src/main/java/org/owen/bookpubstarter/dbcount目录下。
public class DbCountHealthIndicator implements HealthIndicator { private CrudRepository repository;
public DbCountHealthIndicator(CrudRepository repository) { this.repository = repository; }
@Override public Health health() { try { long count = repository.count(); if (count >= 0) { return Health.up().withDetail("count", count).build(); } else { return Health.unknown().withDetail("count", count).build(); } } catch (Exception e) { return Health.down(e).build(); } } } |
- 最后,自动注册我们的HealthIndicator,我修改db-countstarter/src/main/java/org/test/bookpubstarter/dbcount目录下的DbCountAutoConfiguration.java。
@Autowired private HealthAggregator healthAggregator; @Bean public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) { CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator); for (CrudRepository repository : repositories) { String name = DbCountRunner.getRepositoryName(repository.getClass()); compositeHealthIndicator.addHealthIndicator(name, new DbCountHealthIndicator(repository)); } return compositeHealthIndicator; } |
- 启动应用,然后访问:http://localhost:8080/health,你将会看到如下的信息