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

1次阅读

共计 4447 个字符,预计需要花费 12 分钟才能阅读完成。

前言

用过 springboot 的敌人,可能会晓得 springboot 有四大神器:主动拆卸、starter、cli、actuator。其中 actuator 可帮忙你在将应用程序推送到生产环境时监控和管理应用程序。你能够抉择应用 HTTP 端点或 JMX 来治理和监控你的应用程序。审计、衰弱和指标收集也能够主动利用于你的应用程序。

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

ID 形容 默认启用 默认公开
auditevents 公开以后应用程序的审计事件信息 Yes No
beans 显示应用程序中所有 Spring bean 的残缺列表 Yes No
conditions 显示在配置和主动配置类上评估的条件以及它们是否匹配的起因 Yes No
configprops 显示所有 @ConfigurationProperties 对照的列表 Yes No
env 从 Spring 的 ConfigurableEnvironment 中公开属性 Yes No
flyway 显示已利用的任何 Flyway 数据库迁徙 Yes No
health 显示应用程序衰弱信息 Yes Yes
httptrace 显示 HTTP 跟踪信息(默认状况下,最初 100 个 HTTP 申请 - 响应交互) Yes No
info 显示任意应用程序信息 Yes Yes
loggers 显示和批改应用程序中记录器的配置 Yes No
liquibase 显示已利用的任何 Liquibase 数据库迁徙 Yes No
metrics 显示以后应用程序的“指标”信息 Yes No
mappings 显示所有 @RequestMapping 门路对照的列表 Yes No
scheduledtasks 显示应用程序中调度的工作 Yes No
sessions 容许从 Spring Session 反对的会话存储中检索和删除用户会话 Yes No
shutdown 让应用程序优雅地敞开 No No
threaddump 执行线程转储 Yes No

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

ID 形容 默认启用 默认公开
heapdump 返回一个 GZip 压缩的 hprof 堆转储文件 Yes No
jolokia 在 HTTP 上公开 JMX bean(当 Jolokia 在类门路上时,WebFlux 不可用) Yes No
logfile 返回日志文件的内容,反对应用 HTTP Range header 来检索日志文件内容的一部分 Yes No
prometheus 公开指标,该格局能够被 Prometheus 服务器采集 Yes No

注: 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