Chapter 8 SpringBoot index monitoring

Posted by Dtonlinegames on Fri, 04 Feb 2022 15:01:07 +0100

1 SpringBoot Actuator


In the future, after every micro service is deployed on the cloud, we need to monitor, track, audit and control it. SpringBoot extracts the actor scenario, so that we can quickly reference each micro service to obtain production level application monitoring, audit and other functions.


1.2 how to use

  • Introduction scenario

  • visit http://localhost:8080/actuator/ **

  • Expose all monitoring information to HTTP

        enabled-by-default: true #Expose all endpoint information
            include: '*'  #Expose as web

1.3 visualization

2 Actuator Endpoint

2.1 common endpoints

ID describe
auditevents Expose audit event information for the current application. An AuditEventRepository component is required.
beans Displays a complete list of all spring beans in the application.
caches Expose available cache.
conditions Displays all condition information automatically configured, including the reason for matching or not matching.
configprops Show all @ ConfigurationProperties.
env Expose Spring's property ConfigurableEnvironment
flyway Displays all Flyway database migrations that have been applied. One or more Flyway components are required.
health Displays application health information.
httptrace Displays HTTP trace information (by default, the last 100 HTTP request responses). An HttpTraceRepository component is required.
info Displays application information.
integrationgraph The spring integration graph is displayed. You need to rely on spring integration core.
loggers Displays and modifies the configuration of logs in the application.
liquibase Displays all Liquibase database migrations that have been applied. One or more Liquibase components are required.
metrics Displays the indicator information for the current application.
mappings Displays a list of all @ RequestMapping paths.
scheduledtasks Displays scheduled tasks in the application.
sessions Allows user sessions to be retrieved and deleted from the session store supported by Spring Session. A Servlet based Web application using Spring Session is required.
shutdown Close the application normally. Disabled by default.
startup Displays the startup step data collected by ApplicationStartup. BufferingApplicationStartup needs to be configured using spring application.
threaddump Execute thread dump.

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

ID describe
heapdump Returns the hprof heap dump file.
jolokia Expose JMX bean s through HTTP (Jolokia needs to be introduced, not applicable to WebFlux). The dependency Jolokia core needs to be introduced.
logfile Returns the contents of the log file (if the or logging.file.path attribute is set). Support the use of HTTPRange header to retrieve the contents of some log files.
prometheus Publish the indicators in a format that the Prometheus server can grab. You need to rely on micrometer registry Prometheus.

The most commonly used EndPoint.

  • Health: monitoring status
  • Metrics: runtime metrics
  • Loggers: logging

2.2 Health Endpoint

The health check endpoint is generally used in the cloud platform. The platform will regularly check the health status of the application. We need the Health Endpoint to return a collection of the health status of a series of components of the current application for the platform.

  • The result returned by health endpoint should be a summary report after a series of health examinations
  • Many health checks have been automatically configured by default, such as database, redis, etc
  • You can easily add a custom health check mechanism

2.3 Metrics Endpoint

Provide detailed, hierarchical and spatial index information, which can be obtained by pull (active push) or push (passive acquisition).

  • Docking multiple monitoring systems through Metrics
  • Simplify core Metrics development
  • Add custom Metrics or extend existing Metrics

2.4 manage Endpoint

2.4.1 enable and disable endpins

  • By default, all endpoints (except shutdown) are turned on

  • An Endpoint needs to be enabled or disabled. The configuration mode is management Endpoint.. enabled = true

  • You can disable all endpoints and then manually open the specified Endpoint

        enabled-by-default: false
          enabled: true
          enabled: true

2.4.2 exposure Endpoints

Supported exposure methods

  • HTTP: only health and info endpoints are exposed by default

  • JMX: expose all endpoints by default

  • In addition to health and info, the rest of the endpoints should be protected. If spring security is introduced, the security access rules will be configured by default

    ID JMX Web
    auditevents Yes No
    beans Yes No
    caches Yes No
    conditions Yes No
    configprops Yes No
    env Yes No
    flyway Yes No
    health Yes Yes
    heapdump N/A No
    httptrace Yes No
    info Yes Yes
    integrationgraph Yes No
    jolokia N/A No
    logfile N/A No
    loggers Yes No
    liquibase Yes No
    metrics Yes No
    mappings Yes No
    prometheus N/A No
    scheduledtasks Yes No
    sessions Yes No
    shutdown Yes No
    startup Yes No
    threaddump Yes No

3. Customize Endpoint

3.1 customized Health information

The customized Health class name must be xxxHealthIndicator, and xxx is the component name. You can refer to DiskSpaceHealthIndicator

import org.springframework.stereotype.Component;

public class MyHealthIndicator implements HealthIndicator {

    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        return Health.up().build();


structure Health
Health build = Health.down()
                .withDetail("msg", "error service")
                .withDetail("code", "500")
                .withException(new RuntimeException())
      enabled: true
      show-details: always #Always show details. The status information of each module can be displayed
public class MyComHealthIndicator extends AbstractHealthIndicator {

     * Real inspection method
     * @param builder
     * @throws Exception
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        //mongodb.    Get connections for testing
        Map<String,Object> map = new HashMap<>();
        // Check complete
        if(1 == 2){
//            builder.up(); // healthy
        }else {
//            builder.down();
            map.put("err","connection timed out");



3.2 customized info information

There are two common ways.

  • Write configuration file

      appName: boot-admin
      version: 2.0.1
      mavenProjectName: @project.artifactId@  #Use @ @ to get the pom file value of maven
      mavenProjectVersion: @project.version@
  • Write InfoContributor

    import java.util.Collections;
    import org.springframework.stereotype.Component;
    public class ExampleInfoContributor implements InfoContributor {
        public void contribute(Info.Builder builder) {
                    Collections.singletonMap("key", "value"));

    http://localhost:8080/actuator/info All info information returned in the above way will be output

3.3 customized Metrics information

3.3.1 SpringBoot supports automatically adapted Metrics

  • JVM metrics, report utilization of
    • Various memory and buffer pools
    • Statistics related to garbage collection
    • Threads utilization
    • Number of classes loaded/unloaded
  • CPU metrics
  • File descriptor metrics
  • Kafka consumer and producer metrics
  • Log4j2 metrics: record the number of events logged to Log4j2 at each level
  • Logback metrics: record the number of events logged to Logback at each level
  • Uptime metrics: report a gauge for uptime and a fixed gauge representing the application's absolute start time
  • Tomcat metrics (server.tomcat.mbeanregistry.enabled must be set to true for all Tomcat metrics to be registered)
  • Spring Integration metrics

3.3.2 add custom Metrics

class MyService{
    Counter counter;
    public MyService(MeterRegistry meterRegistry){
         counter = meterRegistry.counter("myservice.method.running.counter");

    public void hello() {

//You can also use the following methods
MeterBinder queueSize(Queue queue) {
    return (registry) -> Gauge.builder("queueSize", queue::size).register(registry);

4 customized Endpoint

@Endpoint(id = "container")
public class DockerEndpoint {

    public Map getDockerInfo(){
        return Collections.singletonMap("info","docker started...");

    private void restartDocker(){
        System.out.println("docker restarted....");

Scenario: develop ReadinessEndpoint to manage whether the program is ready or liveness endpoint to manage whether the program is alive.

Topics: Spring