持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天, 点击查看活动详情
对于企业而言,服务的可用性作为重要目标,服务的健康检查和健康,能够清楚的知道服务的健康状态和服务的运行状态,Spring Boot可以通过配置来开启健康检查,并且也能集成到监控工具中,从而监控到服务的运行状态。
集成健康检查
pom文件中添加相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
在application.yml文件中添加相关配置
management:
endpoint:
health:
show-details: always
启动服务,访问/actuator/health接口,获取服务的健康的相关信息.
"status": "UP",
"components": {
"customerHealth": {
"status": "UP"
"db": {
"status": "UP",
"details": {
"database": "MySQL",
"result": 1,
"validationQuery": "/* ping */ SELECT 1"
"diskSpace": {
"status": "UP",
"details": {
"total": 230146699264,
"free": 141040795648,
"threshold": 10485760
"ping": {
"status": "UP"
说明:从输出结果中包含了。包括DB的信息、磁盘的相关信息等。
Spring Boot 提供的健康检查列表如下
CassandraDriverHealthIndicator
CouchbaseHealthIndicator
DataSourceHealthIndicator
ElasticsearchRestHealthIndicator
JmsHealthIndicator
LdapHealthIndicator
MailHealthIndicator
MongoHealthIndicator
RedisHealthIndicator
SolrHealthIndicator
.......
自定义健康检查
针对特殊的健康检查,如果SpringBoot默认提供的不能满足,用户可以进行自定义扩展,实现HealthIndicator接口即可。
例如检查rocketmq是否正常运行
@Component
@ConditionalOnProperty(name="spring.rocketmq.http.send-url")
public class RocketmqHealthIndicator implements HealthIndicator {
@Value("${spring.rocketmq.http.send-url}")
private String rocketmqUrl;
@Override
public Health health()
logger.info("正在检查rocketmq配置项...");
logger.info("rocketmq 请求地址:{}",rocketmqUrl);
Health.Builder up = Health.up().withDetail("url", rocketmqUrl);
try {
HttpUtils.telnet(StringUtils.getIpFromUrl(rocketmqUrl),StringUtils.getPortFromUrl(rocketmqUrl));
return up.build();
} catch (IOException e) {
logger.error("rocketmq配置项错误或网络超时");
return up.withException(e).build();
集成prometheus
Prometheus是一套开源的系统监控报警框架。
pom文件中添加prometheus依赖
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>io.github.mweirauch</groupId>
<artifactId>micrometer-jvm-extras</artifactId>
<version>0.2.0</version>
yml文件中添加prometheus的引用
management:
endpoints:
exposure:
include: *
metrics:
tags:
application: admin
启动项目,访问/actuator/prometheus,即可以获取相关的监控数据
说明:从图中可以看出,prometheus监控了jvm的相关信息。
prometheus中添加项目配置
进入/opt/prometheus/prometheus的目录在prometheus.yml文件中添加引用
- job_name: 'admin'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
metrics_path: "/admin/actuator/prometheus"
static_configs:
- targets: ['172.18.188.12:8480']
job_name:名称
metrics_path :服务访问prometheus的地址,一般为项目名称/actuator/prometheus
targets:监控服务的地址.
重启prometheus
ps -ef | grep prometheus
kill -9 pid
进入启动目录,执行./prometheus &
查看服务是否监控成功
访问prometheus地址:http://ip:9090/targets 地址,如果能够看到如下信息,则说明监控成功
Grafana中的监控显示
说明:从Grafana中能够清楚的查看到服务的相关信息。
本文讲解了Spring Boot实现健康检查和监控,prometheus还提供其他丰富的监控扩展和相关的报警机制,将在后续的文章中进行讲解,如有疑问可以随时反馈。