解析Spring Boot中的Actuator端点

简介: 解析Spring Boot中的Actuator端点

解析Spring Boot中的Actuator端点

今天我们来解析一下Spring Boot中的Actuator端点。Spring Boot Actuator提供了一系列内建的端点,帮助开发者监控和管理Spring Boot应用程序。通过这些端点,可以获取应用的各种运行时信息,极大地方便了开发、运维和故障排查工作。

1. 引入Spring Boot Actuator

首先,我们需要在Spring Boot项目中引入Actuator依赖。在pom.xml文件中添加以下内容:

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

2. 配置Actuator

application.properties文件中进行一些基本配置。可以启用或禁用特定的端点,以及设置端点的访问权限。例如:

management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

上述配置表示暴露所有端点,并且在/actuator/health端点中显示详细信息。

3. 常用Actuator端点解析

3.1 /actuator

/actuator端点提供了所有可用端点的列表。通过访问http://localhost:8080/actuator可以查看所有启用的Actuator端点。

3.2 /actuator/health

/actuator/health端点显示应用程序的健康状况。默认情况下,返回的状态是UPDOWN,可以根据需要自定义健康检查。

package cn.juwatech.health;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class CustomHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        // 自定义健康检查逻辑
        int errorCode = check(); 
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }
    private int check() {
        // 模拟健康检查
        return 0;
    }
}

3.3 /actuator/info

/actuator/info端点显示应用程序的定制信息。可以在application.properties中添加信息,或者在application.yml中配置。

info.app.name=MyApp
info.app.version=1.0.0
info.company.name=Juwatech

访问http://localhost:8080/actuator/info时,会显示上述配置信息。

3.4 /actuator/metrics

/actuator/metrics端点提供了应用程序的各项指标,如JVM内存使用情况、GC活动、线程信息等。通过访问http://localhost:8080/actuator/metrics可以查看所有可用的指标。

package cn.juwatech.metrics;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class CustomMetrics {
    @Autowired
    private MeterRegistry meterRegistry;
    @PostConstruct
    public void init() {
        meterRegistry.gauge("custom.metric", Math.random() * 100);
    }
}

3.5 /actuator/loggers

/actuator/loggers端点显示并可以动态修改日志记录级别。通过访问http://localhost:8080/actuator/loggers可以查看所有的日志记录器及其级别。

package cn.juwatech.logging;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoggerController {
    @PostMapping("/change-log-level")
    public void changeLogLevel(@RequestParam String loggerName, @RequestParam String level) {
        org.apache.logging.log4j.core.config.Configurator.setLevel(loggerName, org.apache.logging.log4j.Level.valueOf(level));
    }
}

4. 自定义Actuator端点

除了内置的端点,Spring Boot还允许我们创建自定义的Actuator端点。

4.1 创建自定义端点

package cn.juwatech.endpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.stereotype.Component;
@Endpoint(id = "custom")
@Component
public class CustomEndpoint {
    @ReadOperation
    public String customRead() {
        return "Custom read operation";
    }
    @WriteOperation
    public void customWrite(String data) {
        // 自定义写操作逻辑
        System.out.println("Custom write operation with data: " + data);
    }
}

4.2 暴露自定义端点

application.properties中配置暴露自定义端点:

management.endpoints.web.exposure.include=custom

访问http://localhost:8080/actuator/custom可以查看自定义的读操作结果。

5. 安全性配置

为了确保Actuator端点的安全,可以配置Spring Security来保护这些端点。

5.1 引入Spring Security依赖

pom.xml中添加Spring Security依赖:

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

5.2 配置安全规则

package cn.juwatech.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.stereotype.Component;
@Component
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/actuator/**").authenticated()
            .and()
            .httpBasic();
        return http.build();
    }
}

这样配置后,所有的Actuator端点都需要进行身份验证才能访问。

6. 总结

Spring Boot Actuator通过提供一系列内建的监控和管理端点,使开发者能够方便地获取应用的运行时信息,并进行管理和调试。通过自定义端点和安全配置,可以进一步增强Actuator的功能和安全性。

相关文章
|
2月前
|
数据采集 人工智能 Java
1天消化完Spring全家桶文档!DevDocs:一键深度解析开发文档,自动发现子URL并建立图谱
DevDocs是一款基于智能爬虫技术的开源工具,支持1-5层深度网站结构解析,能将技术文档处理时间从数周缩短至几小时,并提供Markdown/JSON格式输出与AI工具无缝集成。
128 1
1天消化完Spring全家桶文档!DevDocs:一键深度解析开发文档,自动发现子URL并建立图谱
|
2月前
|
安全 Java API
深入解析 Spring Security 配置中的 CSRF 启用与 requestMatchers 报错问题
本文深入解析了Spring Security配置中CSRF启用与`requestMatchers`报错的常见问题。针对CSRF,指出默认已启用,无需调用`enable()`,只需移除`disable()`即可恢复。对于`requestMatchers`多路径匹配报错,分析了Spring Security 6.x中方法签名的变化,并提供了三种解决方案:分次调用、自定义匹配器及降级使用`antMatchers()`。最后提醒开发者关注版本兼容性,确保升级平稳过渡。
206 2
|
2月前
|
前端开发 安全 Java
Spring Boot 便利店销售系统项目分包设计解析
本文深入解析了基于Spring Boot的便利店销售系统分包设计,通过清晰的分层架构(表现层、业务逻辑层、数据访问层等)和模块化设计,提升了代码的可维护性、复用性和扩展性。具体分包结构包括`controller`、`service`、`repository`、`entity`、`dto`、`config`和`util`等模块,职责分明,便于团队协作与功能迭代。该设计为复杂企业级应用开发提供了实践参考。
101 0
|
26天前
|
安全 Java API
Spring Boot 功能模块全解析:构建现代Java应用的技术图谱
Spring Boot不是一个单一的工具,而是一个由众多功能模块组成的生态系统。这些模块可以根据应用需求灵活组合,构建从简单的REST API到复杂的微服务系统,再到现代的AI驱动应用。
226 8
|
2月前
|
Java 关系型数据库 MySQL
深入解析 @Transactional——Spring 事务管理的核心
本文深入解析了 Spring Boot 中 `@Transactional` 的工作机制、常见陷阱及最佳实践。作为事务管理的核心注解,`@Transactional` 确保数据库操作的原子性,避免数据不一致问题。文章通过示例讲解了其基本用法、默认回滚规则(仅未捕获的运行时异常触发回滚)、因 `try-catch` 或方法访问修饰符不当导致失效的情况,以及数据库引擎对事务的支持要求。最后总结了使用 `@Transactional` 的五大最佳实践,帮助开发者规避常见问题,提升项目稳定性与可靠性。
301 12
|
2月前
|
缓存 安全 Java
深入解析HTTP请求方法:Spring Boot实战与最佳实践
这篇博客结合了HTTP规范、Spring Boot实现和实际工程经验,通过代码示例、对比表格和架构图等方式,系统性地讲解了不同HTTP方法的应用场景和最佳实践。
198 5
|
2月前
|
安全 Java 数据安全/隐私保护
Spring Security: 深入解析 AuthenticationSuccessHandler
本文深入解析了 Spring Security 中的 `AuthenticationSuccessHandler` 接口,它用于处理用户认证成功后的逻辑。通过实现该接口,开发者可自定义页面跳转、日志记录等功能。文章详细讲解了接口方法参数及使用场景,并提供了一个根据用户角色动态跳转页面的示例。结合 Spring Security 配置,展示了如何注册自定义的成功处理器,帮助开发者灵活应对认证后的多样化需求。
84 2
|
2月前
|
前端开发 IDE Java
Spring MVC 中因导入错误的 Model 类报错问题解析
在 Spring MVC 或 Spring Boot 开发中,若导入错误的 `Model` 类(如 `ch.qos.logback.core.model.Model`),会导致无法解析 `addAttribute` 方法的错误。正确类应为 `org.springframework.ui.Model`。此问题通常因 IDE 自动导入错误类引起。解决方法包括:删除错误导入、添加正确包路径、验证依赖及清理缓存。确保代码中正确使用 Spring 提供的 `Model` 接口以实现前后端数据传递。
90 0
|
3月前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
332 29
|
3月前
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
96 4

推荐镜像

更多
  • DNS