Preface

Friends who have used springboot may know that springboot has four artifacts: automatic assembly, starter, cli, and actuator. The actuator can help you monitor and manage applications when they are pushed to the production environment. You can choose to use HTTP endpoints or JMX to manage and monitor your application. Auditing, health and metric collection can also be automatically applied to your application.

The actuator has built-in the following endpoints for us by default

ID Description is enabled by default is public by default
auditeventsExpose the audit event information of the current applicationYesNo
beansDisplay a complete list of all Spring beans in the applicationYesNo
conditionsShows the conditions evaluated on the configuration and auto-configuration classes and the reason why they matchYesNo
configpropsShow a list of @ConfigurationPropertiesYesNo
envExpose properties from Spring's ConfigurableEnvironmentYesNo
flywayShow any Flyway database migrations that have been appliedYesNo
healthDisplay application health informationYesYes
httptraceDisplay HTTP trace information (by default, the last 100 HTTP request-response interactions)YesNo
infoDisplay any application informationYesYes
loggersDisplay and modify the configuration of the recorder in the applicationYesNo
liquibaseShow any Liquibase database migrations that have been appliedYesNo
metricsDisplay "metrics" information of the current applicationYesNo
mappingsDisplay a list of @RequestMappingYesNo
scheduledtasksShow tasks scheduled in the applicationYesNo
sessionsAllows to retrieve and delete user sessions from the session storage supported by Spring SessionYesNo
shutdownLet the application close gracefullyNoNo
threaddumpPerform thread dumpYesNo

If your application is a web application (Spring MVC, Spring WebFlux or Jersey), you can use the following additional endpoints

ID Description is enabled by default is public by default
heapdumpReturn a GZip compressed hprof heap dump fileYesNo
jolokiaExpose JMX beans on HTTP (WebFlux is not available when Jolokia is on the classpath)YesNo
logfileReturn the content of the log file, support the use of HTTP Range header to retrieve part of the content of the log fileYesNo
prometheusPublic indicators, this format can be collected by the Prometheus serverYesNo

Note: actuator has a big difference between springboot 1.X and springboot 2.X, this article uses springboot 2.X as the explanation of this article

Under normal circumstances, the built-in endpoint of the actuator can meet our daily needs, but sometimes we need to customize the endpoint. Here are a few commonly used custom endpoints

Custom endpoint

Custom preconditions, introduced in pom.xml

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

When the built-in health endpoint information is not satisfied to judge whether our project is healthy, we can customize health

By implementing the org.springframework.boot.actuate.health.HealthIndicator interface, it looks like

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

}

Or by inheriting org.springframework.boot.actuate.health.AbstractHealthIndicator, like

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

It is recommended to use this way of inheriting AbstractHealthIndicator. Make the following configuration in the configuration file, you can view detailed health information


management:
   endpoint:
      health:
        show-details: always

by visiting 161494abf919fa http://ip:port/actuator/health, the shape is as follows:


From the picture, we can see that our custom health endpoint information, if @Component does not specify a name, like CustomHealthIndicator, the default is to take custom as the custom endpoint object

2. Custom info

We can expose some of the information we want to display by implementing the org.springframework.boot.actuate.info.InfoContributor interface. Shaped like

@Component
public class CustomInfoContributor implements InfoContributor {

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

}

by visiting 161494abf91a93 http://ip:port/actuator/info, the form is as follows

3. Custom endpoint

Sometimes we need to customize our own endpoint, we can pass
@Endpoint annotation + @ReadOperation, @WriteOperation, @DeleteOperation annotations to implement custom endpoints. The shape is as follows

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

There are more detailed comments in the code snippets, so I won't discuss them here. One detail here is that we need to make the following configuration in yml to expose our custom endpoint

pass through


management:
  endpoints:
    web:
      exposure:
        include: customEndpoint

or


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

Summarize

This article only introduces a few relatively common custom endpoints, more detailed endpoint introduction can be viewed on the official website, the link is as follows

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

demo link

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


linyb极客之路
344 声望193 粉丝