Talk about how the springboot project implements a custom actor endpoint

Time:2022-6-3

preface

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

The following endpoints are built into the actor by default

ID describe Enabled by default Default disclosure
auditevents Expose the audit event information of the current application Yes No
beans Displays a complete list of all spring beans in the application Yes No
conditions Displays the criteria evaluated on the configuration and auto configuration classes and why they match Yes No
configprops Show all@ConfigurationPropertiesList of cross references Yes No
env From spring’sConfigurableEnvironmentPublic properties in Yes No
flyway Show any flyway database migrations that have been applied Yes No
health Show application health information Yes Yes
httptrace Display HTTP trace information (by default, the last 100 HTTP request response interactions) Yes No
info Show any application information Yes Yes
loggers Display and modify the configuration of recorders in the application Yes No
liquibase Show any liquibase database migrations that have been applied Yes No
metrics Show metrics information for the current application Yes No
mappings Show all@RequestMappingList of path cross references Yes No
scheduledtasks Show scheduled tasks in the application Yes No
sessions Allow retrieving and deleting user sessions from the session store supported by spring session Yes No
shutdown Let the application close gracefully No No
threaddump Execute thread dump Yes No

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

ID describe Enabled by default Default disclosure
heapdump Returns a gzip compressedhprofHeap dump file Yes No
jolokia Expose JMX beans over HTTP (Webflux is not available when jolokia is on the classpath) Yes No
logfile Returns the contents of the log file, and supports the use of HTTPRangeHeader to retrieve part of the contents of the log file Yes No
prometheus Public indicators, which can be collected by Prometheus server Yes No

Note:The actor is in springboot 1 X and springboot 2 X is quite different. This article takes springboot 2 X as the explanation of this article

Usually, the built-in endpoint of the actor can meet our daily needs, but sometimes we need to customize the endpoint. Here are some common custom endpoints

Custom endpoint

Custom preconditions, in pom XML import

 <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 enough to judge whether our project is healthy, we can customize health

By implementing org springframework. boot. actuate. health. Healthindicator interface, such as

@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 in the form of

@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 inherit abstracthealthindicator. Make the following configurations in the configuration file to view detailed health information


management:
   endpoint:
      health:
        show-details: always

By visiting http://ip:port/actuator/health View as follows

Talk about how the springboot project implements a custom actor endpoint
From the picture, we can see that if the @component does not specify a name, such as the customhealthindicator, the custom endpoint is taken as the custom endpoint object by default

2. Custom info

We can implement org springframework. boot. actuate. info. Infocontributor interface to expose some information we want to show. Shape as

@Component
public class CustomInfoContributor implements InfoContributor {

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

}

By visiting http://ip:port/actuator/info View as follows

Talk about how the springboot project implements a custom actor endpoint

3. Customize endpoint

Sometimes we need to customize our own endpoints. We can use the
@Endpoint annotations + @readoperation, @writeoperation, @deleteoperation annotations are used to implement custom endpoints. The shape is as follows

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

  //@readoperation corresponds to get request

  /**
   *Request example:
   * 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 corresponds to post request

  /**
   *Request example:
   * POST http://localhost:8080/actuator/customEndpoint
   *
   *Request parameters are in JSON format
   *
   * {
   *     "username": "zhangsan",
   *     "age": 20
   * }
   *
   *The @param username parameter is required
   *The @param age parameter is required
   * @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 corresponds to the delete request

  /**
   *Request example:
   * 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 detailed comments in the code snippet, which are not discussed here. One detail here is that we need to make the following configuration in YML to expose our customized endpoints

adopt


management:
  endpoints:
    web:
      exposure:
        include: customEndpoint

perhaps


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

summary

This article only introduces several relatively common user-defined endpoints. You can view the official website for more detailed endpoint descriptions. The links are 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