preface

Those of you who have used Springboot may know that it has four powers: automatic assembly, starter, CLI, and actuator. In addition, actuator helps you monitor and manage your apps as they are pushed into production. You can choose to use HTTP endpoints or JMX to manage and monitor your application. Auditing, health, and metrics collection can also be applied automatically to your application.

By default, the Actuator has the following endpoints built in for us

ID describe Enabled by default The default public
auditevents Exposes audit event information for 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 references Yes No
env From the SpringConfigurableEnvironmentPublic attributes in Yes No
flyway Displays any Flyway database migrations that have been applied Yes No
health Displays application health information Yes Yes
httptrace Display HTTP trace information (by default, the last 100 HTTP request-response interactions) Yes No
info Displays arbitrary application information Yes Yes
loggers Displays and modifies logger configuration in the application Yes No
liquibase Displays any Liquibase database migrations that have been applied Yes No
metrics Displays metrics information about the current application Yes No
mappings Show all@RequestMappingA list of path comparisons Yes No
scheduledtasks Displays the tasks scheduled in the application Yes No
sessions Allows user sessions to be retrieved and deleted 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 The default public
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. HTTP is supportedRangeHeader to retrieve a portion of the log file contents Yes No
prometheus Expose metrics in a format that can be collected by the Prometheus server Yes No

Note: There is a big difference between springboot 1.X and Springboot 2.X. This article uses Springboot 2.X as its explanation

In general, the endpoints in the actuator can satisfy our daily needs, but sometimes we need to customize the endpoints. Here are a few common custom endpoints

Custom endpoints

Custom preconditions, introduced in POM.xml

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

1. Customize health

We can customize Health when the built-in health endpoint information is not sufficient to determine the health of our project

By implementing org. Springframework. Boot. Actuate. Health. HealthIndicator interface, such as

@Component
public class CustomHealthIndicator implements HealthIndicator {

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

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

Or through inheritance 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(a) {
        // perform some specific health check
        return ThreadLocalRandom.current().nextInt(5); }}Copy the code

AbstractHealthIndicator is recommended. Perform the following operations in the configuration file to view detailed health information


management:
   endpoint:
      health:
        show-details: always
Copy the code

By visiting http://ip:port/actuator/health to view, form as below

As you can see from the image, if @Component does not specify name, like CustomHealthIndicator, the default is to take Custom as the custom endpoint object

2. Customize info

We can realize the org. Springframework. Boot. Actuate. Info. InfoContributor interface, to expose some information we want to show. like

@Component
public class CustomInfoContributor implements InfoContributor {

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

By visiting http://ip:port/actuator/info to view, form as below

3. Customize endpoint

Sometimes we need to customize our endpoints. We can do this with @endpoint annotations + @readOperation, @writeOperation, and @deleteOperation. Form the following

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

  // @readOperation corresponds to the GET request

  / sample request: * * * * * 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 the POST request

  POST/sample request: * * * * * * http://localhost:8080/actuator/customEndpoint request parameters for the json format {* * * "username" : "zhangsan", * "age": 20 * } * *@paramUsername is mandatory *@paramAge is mandatory *@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

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

    return customMap;
  }

Copy the code

There are more detailed comments in the code snippet, which will not be discussed here. One detail here is that we need to do the following configuration in YML to expose our custom endpoints

through


management:
  endpoints:
    web:
      exposure:
        include: customEndpoint
Copy the code

or


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

Copy the code

conclusion

This article introduces only a few relatively common custom endpoints. For more details, see our website

Docs. Spring. IO/spring – the boot…

The demo link

Github.com/lyb-geek/sp…