Spring Boot 3.0中的Actuator端点如何使用?

内容分享4小时前发布
0 1 0

Spring Boot 3.0中的Actuator端点如何使用?

在Spring Boot Actuator功能支持中,提供了一系列的系统监控端点,用来对应用程序进行监控和管理。开发者可以通过这些端点,获取应用程序的健康状况、审计信息、应用程序的详细信息等。下面我们就来详细的看看如何使用Spring Boot3.0中的Actuator功能的使用。

引入依赖

在pom.xml文件中添加Spring Boot Actuator依赖配置,如下所示。

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

配置Actuator端点

在默认的配置状态下,Actuator 端点是禁用的。所以需要在配置文件中开启相关端点的配置内容,如下所示。

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

如果想要开启所有的配置内容,可以通过如下的方式来实现。

management.endpoints.web.exposure.include=*

常用端点介绍

  • health: 显示应用程序的健康状态。
  • info: 显示应用程序的自定义信息。
  • metrics: 提供应用程序的指标信息。
  • env: 显示应用程序的环境属性。
  • beans: 显示应用程序中的所有 Spring beans。
  • mappings: 显示所有的 URL 映射。

示例代码

创建Spring Boot应用

创建一个新的Spring Boot应用程序,并确保pom.xml中包含Actuator依赖,跟上面的配置内容一样。

创建配置


src/main/resources/application.properties中添加配置内容如下所示。

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

创建自定义信息

可以在配置文件中添加如下的自定义信息配置。

info.app.name=My Spring Boot Application
info.app.version=1.0.0
info.app.description=This is a sample Spring Boot application with Actuator.

当然我们也可以通过创建自定义的HealthIndicator或InfoContributor来扩展Actuator端点实现,如下所示。

自定义HealthIndicator

自定义健康指示器,添加自定义的健康配置,如下所示。

package com.example.demo;

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;
    }
}

自定义InfoContributor

自定义一个InfoContributor,用来贡献监控信息内容,如下所示。

package com.example.demo;

import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class CustomInfoContributor implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("customInfo", Collections.singletonMap("key", "value"));
    }
}

添加Controller

创建一个简单的控制器类,用来验证Actuator端点的使用,如下所示。

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot Actuator!";
    }
}

总结

通过上面的步骤,我们就可以在SpringBoot3.0应用程序中对Actuator端点进行使用,用来监控应用程序的运行情况,并且我们还可以使用自定义的Actuator端点来监控和管理你的应用程序,这样可以实现一些应用程序专属监控功能。

© 版权声明

相关文章

1 条评论

  • 头像
    阿兽 读者

    收藏了,感谢分享

    无记录
    回复