Spring Boot添加监控功能Actuator

1.Maven中引入依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>x.x.x</version>
</dependency>

2.在application.properties或者application.yml文件中进行配置。

management:
  endpoints:
    enabled-by-default: true # 暴露所有端点信息
    web:
      exposure:
        include: "*" # 以web方式暴露
3.常用端点使用
  • 健康检查端点:访问http://localhost:8080/actuator/health,可以查看应用的健康状况。如果应用正常运行,通常会返回UP;如果有问题,会返回DOWN并提供相关错误信息
  • 信息端点:访问http://localhost:8080/actuator/info,可以查看应用的基本信息。可以在配置文件中自定义信息
info:
  app:
    name: My Spring Boot Application
    description: This is a sample spring boot application
    version: 1.0.0
  • 指标端点:访问http://localhost:8080/actuator/metrics,可以查看应用的各种指标信息,如内存使用情况、线程池状态、HTTP 请求统计等。还可以访问http://localhost:8080/actuator/metrics/{metricName}查看具体指标的详细信息
  • 环境端点:访问http://localhost:8080/actuator/env,可以查看应用的环境变量和属性信息

自定义端点

可以通过创建一个类并使用@Endpoint注解来定义自定义端点。
java
 
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

@Component
@Endpoint(id = "custom")
public class CustomEndpoint {

    @ReadOperation
    public Map<String, Object> custom() {
        Map<String, Object> map = new HashMap<>();
        map.put("custom", "This is a custom endpoint.");
        return map;
    }
}

端点安全保护

可以使用 Spring Security 来保护端点。以下是一个简单的配置示例:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
               .requestMatchers(AntPathRequestMatcher.antMatcher("/actuator/**")).hasRole("ADMIN")
               .anyrequest().permitall()
               .and()
               .httpBasic();
    }
}
 
posted @   zbb3296  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示