聊聊springboot项目如何实现自定义actuator端点

前言

用过springboot的朋友,可能会知道springboot有四大神器:自动装配、starter、cli、actuator。其中actuator可帮助你在将应用程序推送到生产环境时监控和管理应用程序。你可以选择使用 HTTP 端点或 JMX 来管理和监控你的应用程序。 审计、健康和指标收集也可以自动应用于你的应用程序。

actuator默认为我们内置了以下端点

ID描述默认启用默认公开
auditevents公开当前应用程序的审计事件信息YesNo
beans显示应用程序中所有Spring bean的完整列表YesNo
conditions显示在配置和自动配置类上评估的条件以及它们是否匹配的原因YesNo
configprops显示所有@ConfigurationProperties对照的列表YesNo
env从Spring的ConfigurableEnvironment中公开属性YesNo
flyway显示已应用的任何Flyway数据库迁移YesNo
health显示应用程序健康信息YesYes
httptrace显示HTTP跟踪信息(默认情况下,最后100个HTTP请求-响应交互)YesNo
info显示任意应用程序信息YesYes
loggers显示和修改应用程序中记录器的配置YesNo
liquibase显示已应用的任何Liquibase数据库迁移YesNo
metrics显示当前应用程序的“指标”信息YesNo
mappings显示所有@RequestMapping路径对照的列表YesNo
scheduledtasks显示应用程序中调度的任务YesNo
sessions允许从Spring Session支持的会话存储中检索和删除用户会话YesNo
shutdown让应用程序优雅地关闭NoNo
threaddump执行线程转储YesNo

如果你的应用程序是一个web应用程序(Spring MVC、Spring WebFlux或Jersey),你可以使用以下附加端点

ID描述默认启用默认公开
heapdump返回一个GZip压缩的hprof堆转储文件YesNo
jolokia在HTTP上公开JMX bean(当Jolokia在类路径上时,WebFlux不可用)YesNo
logfile返回日志文件的内容,支持使用HTTP Range header来检索日志文件内容的一部分YesNo
prometheus公开指标,该格式可以被Prometheus服务器采集YesNo

注: actuator 在springboot 1.X 和springboot 2.X 存在较大的差异,本文以springboot 2.X 作为本文的讲解

通常情况下,actuator内置的端点就可以满足我们的日常需求了,但有时候我们需要自定义端点。下面就列举一下几种常用的自定义端点

自定义端点

自定义前置条件,在pom.xml引入

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

1、自定义health

当内置的health端点信息不满足用来判断我们项目是否健康时,我们可以自定义health

通过实现org.springframework.boot.actuate.health.HealthIndicator接口,形如

@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode = check();
        if (errorCode == 1) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    private int check() {
        // perform some specific health check
        return ThreadLocalRandom.current().nextInt(5);
    }

}

或者通过继承org.springframework.boot.actuate.health.AbstractHealthIndicator,形如

@Component("otherCustom")
public class CustomAbstractHealthIndicator extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {

        int errorCode = check();
        if (errorCode == 1) {
            builder.down().down().withDetail("Error Code", errorCode).build();
            return;
        }
        builder.up().build();

    }

    private int check() {
        // perform some specific health check
        return ThreadLocalRandom.current().nextInt(5);
    }
}

推荐使用继承AbstractHealthIndicator 这种方式。在配置文件中作如下配置,可以查看详细的健康信息


management:
   endpoint:
      health:
        show-details: always

通过访问http://ip:port/actuator/health进行查看,形如下


从图片我们可以看出,我们自定义的health端点信息,如果@Component不指定name,形如CustomHealthIndicator ,默认是取custom作为自定义端点对象

2、自定义info

我们可以通过实现org.springframework.boot.actuate.info.InfoContributor接口,来暴露一些我们想展示的信息。形如

@Component
public class CustomInfoContributor implements InfoContributor {

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

}

通过访问http://ip:port/actuator/info进行查看,形如下

3、自定义endpoint

有时候我们需要自定义自己的端点,我们可以通过
@Endpoint注解 + @ReadOperation、@WriteOperation、@DeleteOperation注解来实现自定义端点。形如下

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

  // @ReadOperation 对应GET请求

  /**
   * 请求示例:
   * GET http://localhost:8080/actuator/customEndpoint/zhangsan/20
   * @param username
   * @param age
   *
   * @return
   */
  @ReadOperation
  public Map<String, Object> endpointByGet(@Selector String username,@Selector Integer age) {
    Map<String, Object> customMap = new HashMap<>();
    customMap.put("httpMethod", HttpMethod.GET.toString());
    customMap.put("username",username);
    customMap.put("age",age);
    return customMap;
  }


  // @WriteOperation 对应POST请求

  /**
   * 请求示例:
   * POST http://localhost:8080/actuator/customEndpoint
   *
   * 请求参数为json格式
   *
   * {
   *     "username": "zhangsan",
   *     "age": 20
   * }
   *
   * @param username 参数都为必填项
   * @param age 参数都为必填项
   * @return
   */
  @WriteOperation
  public Map<String, Object> endpointByPost(String username,Integer age) {
    Map<String, Object> customMap = new HashMap<>();
    customMap.put("httpMethod", HttpMethod.POST.toString());
    customMap.put("username",username);
    customMap.put("age",age);
    return customMap;
  }


  // @DeleteOperation 对应Delete请求

  /**
   * 请求示例:
   * DELETE http://localhost:8080/actuator/customEndpoint
   *
   * @return
   */
  @DeleteOperation
  public Map<String, Object> endpointByDelete() {
    Map<String, Object> customMap = new HashMap<>();
    customMap.put("httpMethod", HttpMethod.DELETE.toString());

    return customMap;
  }

代码片段里面有比较详细的注释,这边就不在论述。这边有个细节就是,我们需要在yml作如下配置来暴露我们自定义的端点

通过


management:
  endpoints:
    web:
      exposure:
        include: customEndpoint

或者


management:
  endpoints:
    web:
      exposure:
        include: "*"

总结

本文仅介绍几种相对通用的自定义端点,更详细的端点介绍可以查看官网,链接如下

https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator

demo链接

https://github.com/lyb-geek/springboot-learning/tree/master/springboot-custom-actuator-endpoint

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于生产级别的Java应用程序的框架。而Prometheus是一个开源的监控和警报系统,用于记录和查询应用程序的时间序列数据。在Spring Boot中集成Prometheus可以方便地监控和度量应用程序的性能指标。 要在Spring Boot中集成Prometheus并自定义Prometheus的指标,可以按照以下步骤进行操作: 1. 添加依赖:在Spring Boot项目的pom.xml文件中添加Prometheus相关的依赖。例如: ```xml <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> ``` 2. 配置Prometheus:在Spring Boot项目的配置文件(如application.properties或application.yml)中添加Prometheus相关的配置。例如: ```yaml management: endpoints: web: exposure: include: prometheus ``` 这样配置后,Spring Boot会自动将Prometheus的监控端点暴露出来。 3. 自定义指标:在代码中使用Micrometer库来定义和记录自定义的指标。Micrometer是一个度量库,可以与Prometheus集成。例如,可以使用`Counter`来记录计数器指标,使用`Gauge`来记录度量指标等。以下是一个示例: ```java import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CustomMetrics { private final Counter customCounter; @Autowired public CustomMetrics(MeterRegistry meterRegistry) { customCounter = meterRegistry.counter("custom_counter"); } public void incrementCustomCounter() { customCounter.increment(); } } ``` 在上述示例中,我们定义了一个名为`custom_counter`的计数器指标,并通过`MeterRegistry`将其注册到Micrometer中。 4. 访问指标:启动Spring Boot应用程序后,可以通过访问`/actuator/prometheus`端点来获取Prometheus格式的指标数据。例如,可以使用浏览器或curl命令访问`http://localhost:8080/actuator/prometheus`来获取指标数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值