A, SpringBoot physical

1, ACtuator Introduction

In the future, we will need to monitor, track, audit, and control every microserver deployed on the cloud. SpringBoot abstracts the scene of the Actuator, enabling us to quickly use each micro-service to obtain production-level application monitoring, auditing and other functions.

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

2, 1. the difference between x and 2

3. How to use it

  • The introduction of the scene

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

  • Expose all monitoring information as HTTP

    Management: endpoints: enabled-by-default: true # Expose all endpoints web: exposure: include: ‘*’ # Expose all endpoints in Web mode

  • test

http://localhost:8080/actuator/beans

http://localhost:8080/actuator/configprops

http://localhost:8080/actuator/metrics

http://localhost:8080/actuator/metrics/jvm.gc.pause

http://localhost:8080/actuator/endpointName/detailPath…

4. Visualization

Github.com/codecentric…

Second, the physical Endpoint

1. The most commonly used endpoint

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 caches.

conditions

Displays all condition information for automatic configuration, including the reason for the match or mismatch.

configprops

Display all @ConfigurationProperties.

env

Exposes the Spring 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

Displays the Spring IntegrationGraph. You need to rely on Spring-integration-core.

loggers

Displays and modifies the configuration of logging in the application.

liquibase

Displays all Liquibase database migrations that have been applied. One or more Liquibase components are required.

metrics

Displays metrics information about the current application.

mappings

The list of all @requestMapping paths is displayed.

scheduledtasks

Displays scheduled tasks in the application.

sessions

Allows user sessions to be retrieved and deleted from the Session store supported by Spring Session. Servlet-based Web applications that use Spring Session are required.

shutdown

Close the application properly. This function is disabled by default.

startup

Displays startup step data collected by ApplicationStartup. You need to use SpringApplication configured BufferingApplicationStartup.

threaddump

Perform a 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

Return the hprof heap dump file.

jolokia

Expose JMX beans over HTTP (Jolokia needs to be introduced, not for WebFlux). The jolokia-core dependency needs to be introduced.

logfile

Returns the contents of the log file if the logging.file.name or logging.file.path property is set. Support for retrieving partial log file contents using the HTTPRange header.

prometheus

Expose metrics in a format that the Prometheus server can crawl. Rely on Micrometer-registry-Prometheus.

The most common Endpoint

  • Health: Monitors the status

  • Metrics: runtime Metrics

  • Loggers: logs

2, the Health of the Endpoint

The Health check Endpoint is generally used in the cloud platform, where the platform periodically checks the Health status of the application. Therefore, 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.

Important points:

  • The result returned by the Health endpoint should be a summary report after a series of health checks
  • Many health checks are automatically configured by default, such as database, Redis, etc
  • You can easily add custom health check mechanisms

3, the Metrics of the Endpoint

Provide detailed, hierarchical, and spatial metrics that can be pulled or pushed;

  • Use Metrics to connect to multiple monitoring systems

  • Simplify core Metrics development

  • Add custom Metrics or extend existing Metrics

Manage Endpoints

1. Enable and disable Endpoints

  • By default, all endpoints except shutdown are enabled.

  • An Endpoint needs to be enabled or disabled. Set the mode to management-endpoint.. enabled = true

    management: endpoint: beans: enabled: true

  • Or disable all endpoints and manually enable the specified Endpoint

    management: endpoints: enabled-by-default: false endpoint: beans: enabled: true health: enabled: true

2. Expose Endpoints

Supported exposure mode

  • HTTP: Only health and Info Endpoint are exposed by default
  • JMX: Exposes all endpoints by default
  • All endpoints other than health and INFO should be protected. If SpringSecurity is introduced, secure access rules are 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

Customize the Endpoint

1. Customize Health information

import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealthIndicator implements HealthIndicator { @Override 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(); }} Build Health Health build = health.down ().withdetail (" MSG ", "error service").withdetail ("code", "500") .withException(new RuntimeException()) .build(); Management: Health: enabled: true show-details: always # Always show details. @Component Public class MyComHealthIndicator extends AbstractHealthIndicator {/** * True check method * @param builder * @throws Exception */ @Override protected void doHealthCheck(Health.Builder builder) throws Exception { / / mongo. Map<String,Object> Map = new HashMap<>(); If (1 == 2){// Builder.up (); / / health builder. The status (status. The UP); map.put("count",1); map.put("ms",100); }else { // builder.down(); builder.status(Status.OUT_OF_SERVICE); Map. put("err"," connection timeout "); map.put("ms",3000); } builder.withDetail("code",100) .withDetails(map); }}Copy the code

2. Customize info

There are two ways to do this

1. Write a configuration file

Info: appName: boot-admin version: 2.0.1 mavenProjectName: MavenProjectVersion: @project.version@Copy the code

2. Write InfoContributor

import java.util.Collections; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class ExampleInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail("example", Collections.singletonMap("key", "value")); }}Copy the code

http://localhost:8080/actuator/info will output information returned all the info above way

3. Customize Metrics

SpringBoot supports auto-adaptive 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

2. Add custom Metrics

class MyService{ Counter counter; public MyService(MeterRegistry meterRegistry){ counter = meterRegistry.counter("myservice.method.running.counter"); } public void hello() { counter.increment(); @bean MeterBinder queueSize(Queue Queue) {return (registry) -> Gauge. Builder ("queueSize", queue::size).register(registry); }Copy the code

4. Customize the Endpoint

@Component @Endpoint(id = "container") public class DockerEndpoint { @ReadOperation public Map getDockerInfo(){ return Collections.singletonMap("info","docker started..." ); } @WriteOperation private void restartDocker(){ System.out.println("docker restarted...." ); }}Copy the code

Scenario: Develop a ReadinessEndpoint to manage readiness of the program, or Liveness****Endpoint to manage viability of the program;

IO /spring-boot…