Original: not envy mandarin duck not envy fairy, a line of code half a day. Little Sister Taste (wechat official ID: XjjDog), welcome to share, please reserve the source.

Let’s not say that monitoring is important, don’t spend time in meetings discussing the need for it, and when you have a problem online, don’t suspect monitoring is a waste of development costs. Monitoring allows people to say goodbye to the status quo of “guessing” to maintain the fire, it can leave evidence to support our subsequent analysis.

As the primary objective of monitoring, the viability of the service, that is, its health, becomes Paramount. SpringBoot can enable health checks with simple parameters and can be integrated with mainstream monitoring systems.

Xjjdoc.cn has a detailed classification of 200+ original articles, making it easier to read. Welcome to collect.

1. Enable the monitoring function

In Spring, the actuator component is used for monitoring and related operations. The following starter can be added to the POM:

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

For Gradle, add the following.

dependencies {
  compile("org.springframework.boot:spring-boot-starter-actuator")}Copy the code

Access /actuator/ Health to obtain the health status of the project.

{"status":"UP"}
Copy the code

In the application.yml file, add the following:

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

Visiting this interface again will output the detailed content. The value includes the DB status and disk status. As you can see, the outermost status is actually a collection of internal component states.

{
    "status":"UP"."components": {"db": {"status":"UP"."details": {"database":"H2"."validationQuery":"isValid()"}},"diskSpace": {"status":"UP"."details": {"total":250685575168."free":31373905920."threshold":10485760."exists":true}},"ping": {"status":"UP"}}}Copy the code

2. Customize Indicators

These functions are implemented by Indicators (HealthIndicator). Like the following:

  • DataSourceHealthIndicator
  • DiskSpaceHealthIndicator
  • CouchbaseHealthIndicator
  • MongoHealthIndicator
  • RedisHealthIndicator
  • CassandraHealthIndicator

If you are using a component-provided starter, these indicators are aggregated in the/Health interface and can be turned off in configuration if you don’t want to monitor a component.

management:
  health:
    mongo:
      enabled: false
Copy the code

With this in mind, some components can provide built-in health checks in this way: simply implement the HealthIndicator interface. Example code:

@Component
@Slf4j
public class X implements HealthIndicator {
    @Override
    public Health health(a) {
        try {
            // Check the abnormal component status
        } catch (Exception e) {
            log.warn("Failed to connect to: {}", URL);
            return Health.down()
                    .withDetail("error", e.getMessage())
                    .build();
        }
        returnHealth.up().build(); }}Copy the code

3. Connect to the monitoring system

More often, we want to collect business monitoring data using professional monitoring components. This can be done in SpringBoot using Micrometer.

Taking Prometheus, the most popular, as an example, add the following to the POM.

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Copy the code

Of course, we also need to configure something in YAML. It now looks like this:

management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus
  endpoint:
    health:
      show-details: always
Copy the code

In this case, access /actuator/ Prometheus to obtain monitoring data in Prometheus format.

Similar to the following:

jvm_memory_used_bytes{area="heap",id="PS Survivor Space",} 0.0
jvm_memory_used_bytes{area="heap",id="PS Old Gen",} 2.9444904E7
jvm_memory_used_bytes{area="heap",id="PS Eden Space",} 6.829E7
jvm_memory_used_bytes{area="nonheap",id="Metaspace",} 5.917196E7
jvm_memory_used_bytes{area="nonheap",id="Code Cache",} 1.0929088E7
jvm_memory_used_bytes{area="nonheap",id="Compressed Class Space",} 8420512.0
Copy the code

On the Prometheus target page, you can see the following information:

And finally in Grafana, it’s a little bit more voluptuous.

So what kind of things can it monitor? Let’s take a look:

  • Basic information about service nodes, including memory, CPU, network, and IO
  • JVM stack information
  • JVM GC information, STW information
  • Default HikariCP connection pool information
  • HTTP request interface information (maximum time, highest QPS)
  • Tomcat Container Monitoring
  • Logback Log printing monitoring (Number of logs at each level)
  • . other

As you can see, just by exposing this interface, you can have complete control over the components in your project.

4. Work with the container

Finally, because of the SpringBoot service, it is often published in containers such as Docker. In this case, probes configuration is used (Kube has the same concept). Probes are used to distinguish Liveness from Readiness.

The final configuration is as follows:

management:
  health:
    probes:
      enabled: true
  endpoints:
    web:
      exposure:
        include: health,info,prometheus
  endpoint:
    health:
      show-details: always
Copy the code

At this point, we will get two groups in the browser interface, as shown below:

  • http://localhost:8080/actuator/health/liveness
  • http://localhost:8080/actuator/health/readiness

The former is used to determine whether the container should be restarted; The latter determines whether the service is available and, if so, begins accepting external requests.

End

For small SpringBoot applications, monitoring such as SpringBootAdmin is sufficient. But if your organization is centrally deployed, with many nodes and frequent changes, a unified monitoring and construction platform is necessary.

In addition to Prometheus, SpringBoot Metrics supports the following components:

  • AppOptics
  • Atlas
  • Datadog
  • Dynatrace
  • Elastic
  • Ganglia
  • Graphite
  • Humio
  • Influx
  • JMX
  • KairosDB
  • New Relic
  • Prometheus
  • SignalFx
  • Simple (in-memory)
  • Stackdriver
  • StatsD
  • Wavefront

Are there any familiar components?

Xjjdog is a public account that doesn’t allow programmers to get sidetracked. Focus on infrastructure and Linux. Ten years architecture, ten billion daily flow, and you discuss the world of high concurrency, give you a different taste. My personal wechat xjjdog0, welcome to add friends, further communication.