Spring Boot Actuator是一个强大的子项目,它为Spring Boot应用程序提供了生产级别的监控和管理功能。通过Actuator,开发者可以轻松地获取应用程序的运行状态、性能指标、配置信息等,而无需自己实现这些功能。
/actuator/health
){
"status": "UP",
"components": {
"db": {
"status": "UP",
"details": {
"database": "H2",
"validationQuery": "isValid()"
}
},
"diskSpace": {
"status": "UP",
"details": {
"total": 500105249792,
"free": 356682842112,
"threshold": 10485760
}
}
}
}
/actuator/info
){
"app": {
"name": "demo-application",
"version": "1.0.0",
"description": "Spring Boot Actuator Demo"
},
"build": {
"artifact": "demo",
"name": "demo",
"time": "2023-05-15T12:40:12.123Z",
"version": "1.0.0",
"group": "com.example"
}
}
/actuator/metrics
){
"names": [
"jvm.memory.max",
"process.uptime",
"system.cpu.count",
"jvm.threads.live",
"logback.events"
]
}
/actuator/env
){
"activeProfiles": ["dev"],
"propertySources": [
{
"name": "server.ports",
"properties": {
"local.server.port": {
"value": 8080
}
}
},
{
"name": "servletContextInitParams",
"properties": {}
}
]
}
pom.xml
:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application.properties
或application.yml
中):# 暴露所有端点(生产环境慎用)
management.endpoints.web.exposure.include=*
# 或选择性暴露
management.endpoints.web.exposure.include=health,info,metrics
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// 实现自定义健康检查逻辑
boolean isHealthy = checkSomething();
if (isHealthy) {
return Health.up()
.withDetail("customService", "Available")
.build();
}
return Health.down()
.withDetail("customService", "Not Available")
.build();
}
}
@Component
public class CustomInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("customInfo",
Collections.singletonMap("description", "This is custom info"));
}
}
为了保护敏感端点,建议配置安全访问:
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/info").permitAll()
.antMatchers("/actuator/**").hasRole("ADMIN")
.and()
.httpBasic();
}
}
@Service
public class MyService {
private final Counter counter;
public MyService(MeterRegistry registry) {
this.counter = registry.counter("my.service.calls");
}
public void doSomething() {
// 业务逻辑
counter.increment();
}
}
@Endpoint(id = "features")
@Component
public class FeaturesEndpoint {
private Map<String, Boolean> features = new ConcurrentHashMap<>();
@ReadOperation
public Map<String, Boolean> features() {
return features;
}
@WriteOperation
public void configureFeature(@Selector String name, boolean enabled) {
features.put(name, enabled);
}
}
通过合理配置和使用Spring Boot Actuator,你可以轻松实现应用程序的全面监控和管理,大大提高生产环境的可观察性和运维效率。