赞
踩
Spring Boot Actuator 是一个非常强大的功能模块,它提供了一系列的端点(Endpoints),用于监控和管理应用的各个方面,包括但不限于健康检查、度量指标、审计、环境信息等。下面是如何在Spring Boot应用中使用Actuator的实战指南:
在pom.xml
中添加Spring Boot Actuator的依赖。对于Spring Boot 2.x及以后的版本,默认已经包含了Actuator,但你可以通过添加spring-boot-starter-actuator
来确保所有功能可用:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
在application.properties
或application.yml
中配置Actuator端点的暴露方式和细节。为了安全起见,生产环境中建议只暴露必要的端点,并通过安全机制保护它们。
management.endpoints.web.exposure.include=health,info,metrics # 指定要暴露的端点
management.endpoint.health.show-details=always # 显示健康检查的详细信息
management.server.port=8081 # 可以设置独立的管理端口
/health
:提供应用健康状态的概览,包括数据库连接、磁盘空间等。/info
:展示应用的元数据,如版本号、构建时间等,这些信息通常通过application.properties
或application.yml
中的info.*
属性提供。/metrics
:提供应用的各种度量指标,如内存使用情况、线程信息、HTTP请求统计等。/env
:展示应用的环境变量和配置属性。/loggers
:允许动态地查看和修改应用日志级别。/shutdown
:提供应用的关闭操作(默认情况下不启用,需要手动配置)。在生产环境中,确保Actuator端点的安全至关重要。你可以使用Spring Security来保护这些端点,例如:
management.security.enabled=true # 启用安全保护
security.user.name=admin # 登录用户名
security.user.password=secret # 登录密码
对于Spring Boot 2.0以上版本,推荐使用Spring Security的自动配置,并通过角色基础的访问控制来保护端点。
启动Spring Boot应用后,可以通过浏览器或命令行工具访问这些端点。例如,访问http://localhost:8080/actuator/health
来查看应用健康状况。
你可以自定义端点来满足特定的监控需求。创建一个类,添加@Endpoint
注解,并实现Endpoint
接口,然后在配置中将其包含进暴露的端点列表中。
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
@Component
@Endpoint(id = "customEndpoint")
public class CustomEndpoint {
@ReadOperation
public Map<String, Object> customInfo() {
Map<String, Object> info = new HashMap<>();
info.put("message", "Hello from custom endpoint");
return info;
}
}
如果你的应用需要与Prometheus这样的监控系统集成,可以添加micrometer-registry-prometheus
依赖,并配置Actuator以暴露Prometheus端点:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
然后,访问/actuator/prometheus
端点,就可以直接从Prometheus抓取监控数据。
通过以上步骤,你就能充分利用Spring Boot Actuator的强大功能,实现应用的有效监控和管理。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。