一、 spring boot actuator 概述
spring boot actuator是spring boot 提供的生产级监控与管理工具集,用于实时监控和运维管理应用。actuator 通过http 端点(或 jmx 端点)暴露应用的健康状态、性能指标、日志信息、环境配置等关键数据,使开发者和运维人员能够高效地监测应用状态、优化性能、排查问题,尤其适用于生产环境。
核心功能:
1.健康检查(health checks)
• 提供应用的运行健康状态,可监控数据库、缓存、消息队列等依赖服务,通常用于服务可用性探测(如 kubernetes 健康检查)。
• 通过/actuator/health端点访问,返回up(正常)或 down(异常),支持自定义健康检查。
2.度量指标(metrics)
• 提供应用的性能指标,包括jvm 内存使用、gc 状态、线程数、数据库连接池状态等。
• 通过/actuator/metrics端点访问,可与prometheus、grafana、micrometer结合,实现完整的应用监控方案。
3.日志管理(logging)
• 通过/actuator/loggers端点,支持实时调整日志级别,避免生产环境修改配置后必须重启应用的麻烦。
• /actuator/logfile端点可直接查看应用日志文件(需额外配置logging.file.name或logging.file.path)。
4.环境信息(environment info)
• 通过/actuator/env端点,查看应用当前的环境变量、配置属性、系统参数等,方便排查配置问题。
• /actuator/configprops端点可查看所有@configurationproperties 配置项,直观了解 spring boot 自动配置细节。
二、 集成 spring boot actuator
spring boot actuator 提供了一套开箱即用的监控和管理工具,集成非常简单,只需添加依赖、启用端点并配置访问权限即可。
步骤1:maven 依赖配置
在pom.xml文件中引入 spring boot actuator 依赖。
<dependencies>
<!-- spring boot actuator -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-actuator</artifactid>
</dependency>
</dependencies>添加依赖后,actuator 的部分端点会默认启用,无需额外代码即可使用。
步骤2: 启用 actuator 端点
actuator 端点分为默认启用端点和需手动启用端点。
默认启用的端点:
• /actuator/health:应用健康状况
• /actuator/info:应用基本信息
非默认启用端点:
以下端点默认可用但未暴露,需要手动启用:
• /actuator/metrics:应用性能指标(jvm 内存、gc、请求数等)
• /actuator/env:应用环境变量、系统属性
• /actuator/logfile:访问日志文件(需额外配置日志路径)
• /actuator/heapdump:下载 jvm 堆转储文件
• /actuator/threads:查看线程信息
• /actuator/configprops:查看@configurationproperties配置项
• /actuator/caches:查看缓存状态
• /actuator/beans:列出 spring beans
• /actuator/auditevents:spring security 审计事件
启用非默认端点
在application.properties或application.yml中配置。
在 application.properties 中:
# 启用指定端点
management.endpoints.web.exposure.include=metrics,logfile
# 启用所有端点
management.endpoints.web.exposure.include=*
在 application.yml 中:
management:
endpoints:
web:
exposure:
include: env,metrics配置日志路径(适用于 /logfile 端点)
/logfile端点显示暴露后,还需在application.properties配置日志文件路径:
management.endpoint.logfile.external-file=/var/log/myapp.log
步骤3:访问actuator端点
1.访问健康检查端点(health check):
http://localhost:8080/actuator/health
响应示例:
{
"status": "up"
}• up表示应用正常运行。
• down表示应用不健康。
• out_of_service表示应用正在停止。
2.访问度量指标端点(metrics):
http://localhost:8080/actuator/metrics
响应示例:
{
"names": [
"jvm.memory.used",
"jvm.gc.pause",
"http.server.requests"
]
}访问特定指标,查看具体数值:
http://localhost:8080/actuator/metrics/jvm.memory.used
返回的内容:
{
"name": "jvm.memory.used",
"measurements": [
{
"statistic": "value",
"value": 12345678
}
],
"availabletags": [
{
"tag": "area",
"values": ["heap", "non-heap"]
}
]
}3.访问信息端点(info):
http://localhost:8080/actuator/info
响应示例:
{
"app": {
"name": "myapp",
"version": "1.0.0"
}
}三、 自定义 actuator 端点
spring boot actuator 提供了丰富的内置端点,但在某些情况下,需要自定义端点以满足特定的监控需求。actuator 支持两种方式创建自定义端点:
• 实现 endpoint 接口
• 继承 abstractendpoint(已在较早版本使用,现推荐 @endpoint 注解方式)
步骤1:创建自定义端点类
简单示例:
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 "这是自定义的 actuator 端点";
}
}代码解析:
• @endpoint(id = “custom”):定义自定义端点/actuator/custom。
• @readoperation:指定该方法用于 get 请求,返回端点的数据。
步骤2:配置暴露自定义端点
默认情况下,spring boot 仅暴露health和info端点。要使自定义端点可访问,需要在application.properties或application.yml配置:
management.endpoints.web.exposure.include=custom
或在application.yml中:
management:
endpoints:
web:
exposure:
include: custom步骤3:访问自定义端点
应用启动后,可通过以下 url 访问:
http://localhost:8080/actuator/custom
响应:
"这是自定义的 actuator 端点"
四、端点扩展
在 spring boot actuator 中,除了自定义端点,还可以对已有端点进行扩展,以增强其功能。在不重新创建端点的情况下,满足特定业务需求。
1. 扩展健康检查(healthindicator)
/actuator/health端点默认检查应用的基本健康状态。我们可以通过实现healthindicator接口,扩展健康检查逻辑,例如,检查应用的数据库连接、第三方服务的状态等。
代码示例:检查数据库是否正常
@component
public class databasehealthindicator implements healthindicator {
@override
public health health() {
// 数据库连接检查
boolean isdatabasehealthy = checkdatabase();
// 根据数据库健康状态返回健康状态
if (isdatabasehealthy) {
return health.up().withdetail("database", "ok").build();
} else {
return health.down().withdetail("database", "not reachable").build();
}
}
// 模拟数据库连接检查的方法
private boolean checkdatabase() {
// 这里可以写实际的数据库连接检查逻辑
// 如,通过 jdbc 或连接池检查数据库连接
return true; // 假设数据库连接正常
}
}代码解析:
• @component: 标记databasehealthindicator为 spring bean,确保被 spring 扫描并注册。
• healthindicator接口:自定义健康检查逻辑的基类。
• health():检查数据库连接。正常返回up,否则返回down。
健康检查结果:
访问/actuator/health,如果数据库正常:
{
"status": "up",
"details": {
"database": "ok"
}
}
如果数据库不可用:
{
"status": "down",
"details": {
"database": "not reachable"
}
}
2. 扩展日志管理(动态修改日志级别)
/actuator/logfile端点提供了日志内容的查看功能。spring boot 允许通过logback-spring.xml配置文件动态控制日志级别。
代码示例:
<configuration>
<!-- 控制根日志级别为info -->
<root level="info">
<appender-ref ref="console"/>
</root>
<!-- 定义日志级别为debug -->
<logger name="com.example" level="debug"/>
<!-- 控制日志输出格式 -->
<appender name="console" class="ch.qos.logback.core.consoleappender">
<encoder>
<pattern>%d{yyyy-mm-dd hh:mm:ss} - %msg%n</pattern>
</encoder>
</appender>
</configuration>代码解析:
• <root level="info">: 设置根日志级别为info,即显示info及更高级别的日志(如warn,error)。 • <logger name="com.example" level="debug"/>: 为特定包(com.example)设置debug级别日志,使得它显示更多细节。 • <appender>: 定义日志输出方式(例如,输出到控制台)。
动态修改日志级别:
通过/actuator/loggers端点动态修改日志级别,例如:
1.查看当前日志级别:
get /actuator/loggers/com.example
2.动态修改日志级别:
post /actuator/loggers/com.example
content-type: application/json
{
"configuredlevel": "debug"
}
修改后,日志系统会立即生效,而无需重启应用。
3. 扩展度量指标(metrics)
使用meterregistry注册自定义指标,例如,添加自定义计数器:
@component
public class custommetrics {
private final meterregistry meterregistry;
public custommetrics(meterregistry meterregistry) {
this.meterregistry = meterregistry;
}
@postconstruct
public void init() {
counter counter = meterregistry.counter("custom.counter");
counter.increment(); // 每次调用时递增
}
}访问/actuator/metrics可查看custom.counter指标。
4. 其他常见端点扩展
除了健康检查、度量指标和日志管理,spring boot actuator 还支持其他端点的扩展,以提供更丰富的监控和管理能力,例如:
• 环境配置(environment)
通过扩展/actuator/env端点,可以暴露更多的环境变量或系统属性,以便在运行时查看和调试应用配置。
• 审计事件(audit events)
通过扩展/actuator/auditevents端点,可以自定义审计事件的记录和查询,例如用户登录、权限变更等关键事件的追踪。
• 配置属性(config props)
通过扩展/actuator/configprops端点,可以暴露更多的应用配置属性,以便分析 spring boot 自动配置的内容,帮助开发者更好地理解应用的运行状态。
总结
• 自定义端点:使用@endpoint创建新端点,如/actuator/custom。
• 端点扩展:
• 健康检查:使用healthindicator扩展/actuator/health。
• 日志管理:通过/actuator/loggers端点动态调整日志级别。
• 度量指标:使用meterregistry添加自定义指标。
五、端点安全管理
为了确保 spring boot actuator 端点的访问安全,推荐使用 spring security 配置权限控制。以防止未授权的访问,保护敏感数据。以下是配置端点安全的基本步骤:
步骤1:引入 spring security 依赖
在pom.xml文件中添加 spring security 依赖:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid>
</dependency>步骤2:配置安全策略
使用@enablewebsecurity注解和websecurityconfigureradapter配置 actuator 端点的访问权限,例如:
@configuration
@enablewebsecurity
public class securityconfig extends websecurityconfigureradapter {
@override
protected void configure(httpsecurity http) throws exception {
http
.authorizerequests()
.antmatchers("/actuator/**").hasrole("admin") // 仅允许 admin 角色访问
.anyrequest().authenticated() // 其他请求需认证
.and()
.httpbasic(); // 启用基本认证
}
}步骤3:配置用户名和密码
spring boot 默认会生成随机用户名和密码。要使用自定义凭据,可在application.properties或application.yml配置:
spring.security.user.name=admin spring.security.user.password=secret
步骤4:精细化保护 actuator 端点
配置哪些端点对外开放。例如:
management.endpoints.web.exposure.include=health,info // 开放 health 和 info 端点 management.endpoints.web.exposure.exclude=metrics,env // 排除 metrics 和 env 端点
端点安全的最佳实践:
• 最小化暴露端点:仅开放必要的端点,减少安全风险。
• 使用角色权限控制:确保敏感端点只能由特定角色访问。
• 启用 https:在生产环境中,强制使用 https 保护数据传输安全。
• 结合 api 网关或身份认证服务:如 keycloak、oauth2 进行细粒度访问控制。
通过以上安全策略,可以有效保护 actuator 端点,确保监控数据的安全性。
六、监控与管理常用示例
spring boot actuator 提供了丰富的端点,可用于监控和管理应用。下面介绍几个常见的使用场景,帮助你在生产环境中高效监控应用状态。
1. 健康检查端点的应用
健康检查是 actuator 最常用的功能之一,常用于:
• 应用存活检测:判断服务是否正常运行,可用于负载均衡器的健康检查。
• 外部依赖检查:检测数据库、缓存、第三方 api 是否可用,保障系统稳定性。
最佳实践
• 自定义健康检查
如,检查数据库状态、mq 消息队列是否正常。
• 与负载均衡器集成
负载均衡器(如 nginx、kubernetes)可通过/actuator/health判断服务健康状态,自动进行流量分配或故障转移。
2.自定义度量指标的应用
actuator 端点/actuator/metrics提供 jvm 运行时、线程池、http 请求等性能指标。可以使用meterregistry添加自定义度量指标。
最佳实践:
• 添加 api 请求计数、耗时统计:监控接口调用频率和性能瓶颈。
• 集成 prometheus/grafana:通过可视化工具实时查看度量数据。
3.日志管理扩展
日志是调试和运维的重要工具,actuator 允许动态修改日志级别,无需重启应用。
最佳实践:
• 生产环境下,日志级别默认设置为 warn 或 error,仅记录关键信息。
• 调试时,可动态调整为 debug 级别,快速排查问题。
• 结合 elk(elasticsearch + logstash + kibana)等日志分析工具,提高故障诊断效率。
七、总结
1. 核心要点
• 集成 spring boot actuator
提供开箱即用的监控和管理功能,帮助监控应用健康和性能。
• 自定义和扩展端点
可根据业务需求定制健康检查、度量指标等,扩展 actuator 的功能。
• 端点安全管理
使用 spring security 配置权限控制,确保端点访问的安全性
到此这篇关于spring boot actuator - 应用监控与管理的文章就介绍到这了,更多相关spring boot actuator监控内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论