Spring Boot Actuator 是一个强大的监控和管理工具,允许开发者快速获取应用的运行状态、性能指标和配置细节。它特别适合用于微服务架构中,帮助开发者更好地监控和管理服务。
什么是 Spring Boot Actuator?
Spring Boot Actuator 是 Spring Boot 提供的一个独立模块,旨在通过简单的方式提供应用程序的监控和管理功能。Actuator 内置了多种端点(Endpoints),可以用于查看应用的健康状况、配置属性、日志级别等。
核心特性
- 健康检查:检查应用程序和其依赖服务(如数据库、消息队列等)的健康状态。
- 性能指标:提供 JVM 内存使用情况、线程池信息、请求处理时间等详细指标。
- 应用信息:展示应用的版本、配置属性和环境变量等信息。
- 动态管理:可以动态修改日志级别或其他运行时配置。
- 安全集成:支持对端点的访问控制和认证。
如何启用 Actuator
1. 添加依赖
在 pom.xml
中添加 Actuator 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
对于 Gradle:
implementation 'org.springframework.boot:spring-boot-starter-actuator'
2. 配置端点
在 application.properties
或 application.yml
中启用所需的端点:
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*
:公开所有端点。management.endpoint.health.show-details=always
:在健康检查中显示详细信息。
常用端点
Spring Boot Actuator 提供了丰富的内置端点,以下是一些常用端点:
端点 | 描述 | 示例 URL |
---|---|---|
/actuator/health |
检查应用程序的健康状态 | http://localhost:8080/actuator/health |
/actuator/info |
查看应用程序的基本信息 | http://localhost:8080/actuator/info |
/actuator/metrics |
查看性能指标 | http://localhost:8080/actuator/metrics |
/actuator/loggers |
动态修改日志级别 | http://localhost:8080/actuator/loggers |
/actuator/env |
查看应用的环境属性 | http://localhost:8080/actuator/env |
示例
健康检查
访问 http://localhost:8080/actuator/health
:
{
"status": "UP",
"components": {
"db": {
"status": "UP",
"details": {
"database": "MySQL",
"validationQuery": "isValid()"
}
},
"diskSpace": {
"status": "UP",
"details": {
"total": 5000000000,
"free": 3000000000
}
}
}
}
性能指标
访问 http://localhost:8080/actuator/metrics
,获取可用指标:
{
"names": [
"jvm.memory.used",
"jvm.memory.max",
"http.server.requests",
"system.cpu.usage"
]
}
然后访问具体指标,例如 http://localhost:8080/actuator/metrics/jvm.memory.used
:
{
"name": "jvm.memory.used",
"measurements": [
{
"statistic": "VALUE",
"value": 12345678
}
],
"availableTags": [
{
"tag": "area",
"values": [
"heap",
"nonheap"
]
}
]
}
安全配置
Actuator 提供了强大的安全机制,防止敏感信息泄露。
1. 配置基本认证
在 application.properties
中启用 Spring Security:
spring.security.user.name=admin
spring.security.user.password=secret
访问端点时,需要提供用户名和密码。
2. 限制端点访问
通过以下配置控制访问权限:
management.endpoints.web.exposure.include=health,info
以上配置仅公开 /health
和 /info
端点。
自定义端点
Actuator 允许开发者自定义端点以满足特定需求。
示例:创建一个自定义端点
代码示例
package com.example.demo.actuator;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
@Component
@Endpoint(id = "custom")
public class CustomEndpoint {
@ReadOperation
public String customEndpoint() {
return "This is a custom endpoint";
}
}
配置
添加自定义端点后,访问 http://localhost:8080/actuator/custom
,将返回:
This is a custom endpoint
总结
Spring Boot Actuator 是开发者在生产环境中监控和管理应用的利器。通过内置的端点和丰富的指标支持,开发者可以快速识别问题、优化性能,并确保系统的稳定性和高效运行。同时,Actuator 还提供了高度的可扩展性,支持自定义端点和安全配置。
感谢关注点赞收藏!