Tùy chỉnh Điểm cuối Actuator trong Spring Boot

Tổng quan về Spring Boot Actuator

Spring Boot Actuator cung cấp khả năng giám sát ứng dụng thông qua các điểm cuối (endpoints) tích hợp sẵn, cho phép theo dõi trạng thái hoạt động, hiệu năng và môi trường thực thi.

Chức năng chính

  • Kiểm tra sức khỏe: Điểm cuối /actuator/health xác định tình trạng ứng dụng
  • Đo lường hiệu suất: /actuator/metrics cung cấp chỉ số JVM và HTTP
  • Thông tin môi trường: /actuator/env hiển thị cấu hình biến môi trường

Triển khai kỹ thuật

Cấu hình dependency trong Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Quản lý hiển thị điểm cuối:

management.endpoints.web.exposure.include=health,info
management.endpoints.web.exposure.exclude=env

Triển khai Điểm cuối Tùy chỉnh

Tạo điểm cuối mới

Định nghĩa lớp với annotation @Endpoint:

@Endpoint(id = "serviceStatus")
@Component
public class ServiceMonitor {

    @ReadOperation
    public Map<String, Object> getServiceStatus() {
        return Map.of(
            "activeServices", 5,
            "status", "OPERATIONAL"
        );
    }
}

Truy cập qua: GET /actuator/serviceStatus

Tùy chỉnh đường dẫn và cổng

management:
  endpoints:
    web:
      base-path: /admin
  server:
    port: 8888

Đường dẫn mới: http://localhost:8888/admin/serviceStatus

Bảo mật điểm cuối

Cấu hình Spring Security:

@Configuration
public class EndpointSecurity extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/health").permitAll()
            .antMatchers("/admin/**").hasAuthority("ADMIN")
            .and().httpBasic();
    }
}

Kịch bản ứng dụng

Theo dõi số liệu nghiệp vụ:

@Endpoint(id = "transactionStats")
@Component
public class TransactionEndpoint {

    @ReadOperation
    public Map<String, Number> transactionMetrics() {
        return Map.of(
            "pendingTransactions", 12,
            "avgProcessTime", 45
        );
    }
}

Cập nhật cấu hình động:

@Endpoint(id = "configManager")
@Component
public class DynamicConfig {

    private String cacheMode = "LRU";

    @WriteOperation
    public String setCacheMode(String mode) {
        this.cacheMode = mode;
        return "Cache mode updated: " + mode;
    }
}

Thẻ: spring-boot Actuator custom-endpoint Java spring-security

Đăng vào ngày 22 tháng 7 lúc 23:44