项目场景:
项目场景:之前项目遇到过mysql数据库的服务器CPU利用率高达百分之90多,导致连接数据库超时的问题,然后前端就提需求,说要给一个接口能监测数据库的状态。
解决方案:
使用actuator监测项目健康状态。
导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置:
application.yml的配置
management:
endpoints:
web:
exposure:
include: "health" # 这里可以改为"*",这样的话可以获取到更多监测信息
base-path: /actuator # 建议修改访问路径,防止被不法分子通过这个路径拿到你项目的信息
endpoint:
health:
show-details: always
application.properties的配置
# 这里可以改为"*",这样的话可以获取到更多监测信息
management.endpoints.web.exposure.include=health
# 建议修改访问路径,防止被不法分子通过这个路径拿到你项目的信息
management.endpoints.web.base-path=/actuator
management.endpoint.health.show-details=always
然后启动项目,通过配置的management.endpoints.web.base-path路径加上/health访问,即可查看当前项目和数据库的状态
正常情况:
{
status: "UP",
components: {
db: {
status: "UP",
details: {
database: "MySQL",
validationQuery: "SELECT 1",
result: 1
}
},
diskSpace: {
status: "UP",
details: {
total: 107375226880,
free: 48313511936,
threshold: 10485760,
exists: true
}
},
ping: {
status: "UP"
},
redis: {
status: "UP",
details: {
version: "3.2.100"
}
}
}
}
报错情况:
{
status: "UP",
components: {
db: {
status: "UP",
details: {
error: "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLTransientConnectionException: DatebookHikariCP - Connection is not available, request timed out after 1006ms."
}
},
diskSpace: {
status: "UP",
details: {
total: 107375226880,
free: 48313511936,
threshold: 10485760,
exists: true
}
},
ping: {
status: "UP"
},
redis: {
status: "UP",
details: {
version: "3.2.100"
}
}
}
}
可以看到这里面就展示了数据库的状态,以及数据库不正常时的报错信息