Spring Boot Actuator 是Spring Boot应用监控和管理的强大工具集,它提供了丰富的端点(Endpoints)用于健康检查、性能监控及应用配置信息查看等。本文旨在深入浅出地介绍Actuator的使用、常见问题、易错点及其规避策略,并附上实用的代码示例。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
health
和info
是公开的,但其他端点需要显式开启。management.endpoints.web.exposure.include=health,info,metrics,env,loggers
HealthIndicator
接口来自定义健康检查逻辑。@Component
public class CustomHealthCheck implements HealthIndicator {
@Override
public Health health() {
// 检查逻辑...
if (/* 健康 */) {
return Health.up().withDetail("custom", "OK").build();
} else {
return Health.down().withDetail("custom", "Not OK").build();
}
}
}
application.properties
中设置management.endpoint.health.show-details=when_authorized
并配置安全认证。/actuator/metrics
端点查看应用的各项指标。Counter
, Gauge
, Timer
等进行。@Autowired
private MeterRegistry registry;
public void recordCustomMetric() {
Counter counter = registry.counter("myapp.requests");
counter.increment();
}
management.security.enabled=true
或在Spring Boot 2.x及以上版本使用Spring Security配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/**").hasRole("ACTUATOR")
.and()
.httpBasic();
}
}
/actuator/loggers
端点调整日志级别。/actuator/env
端点获取当前应用环境变量信息。Spring Boot Actuator是提升应用可观察性和维护性的强大工具。正确配置和使用它,不仅可以帮助开发者快速定位问题,还能在生产环境中提供必要的监控和管理能力。通过上述介绍和示例,希望能帮助你更好地理解和运用Actuator,为你的微服务架构增添一份保障。在实践中不断探索,根据具体需求灵活调整配置,是发挥Actuator最大效能的关键。