Principle of SpringBoot Automatic assembly A customized SpringBoot Starter

Physical (monitoring)

1. The physical is introduced

Through the previous introduction, we understand why SpringBoot is able to easily and quickly build Web applications, so how to find the health problems after the application is deployed online? In SpringBoot we provide Actuator to solve this problem.

Spring. IO /spring-boot…

Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application.

Spring Boot includes a number of additional features to help you monitor and manage applications as they are put into production. You can choose to use HTTP endpoints or use JMX to manage and monitor applications. Auditing, health, and measurement collection can also be automatically applied to your application.

To use Actuator we need to add dependencies

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

2. The endpoint (Endpoints)

Endpoints can be used to monitor and interact with applications. Spring Boot includes many built-in endpoints, and you can add your own. For example, the Health endpoint provides basic health information for the application. Each endpoint can be enabled or disabled. This controls whether the endpoint is created and whether its beans exist in the application context. To access the endpoints remotely, you must also expose them via JMX or HTTP; HTTP is chosen for most applications, and the ID of the endpoints is mapped to a URL prefixed with /. For example, the HEALTH endpoint maps to /actuator/health by default.

Note: The base path of the endpoints in Spring Boot 2.0 is changed from “/” to “/info”. For example, if /info is changed to /actuator/info, the configuration can be changed to be consistent with the old version:

management.endpoints.web.base-path=/
Copy the code

By default, only the Health and info endpoints are released.

To release more endpoints, you need to configure the following information

management.endpoints.web.exposure.include=*
Copy the code

The following is the Endpoint provided in SpringBoot.

ID describe Enabled by default
auditevents Display the audit event information of the current application Yes
beans Display an applicationAll Spring BeansComplete list of Yes
conditions According toConfiguration and autoconfiguration classes(Configuration and auto-configuration classes) and why they are applied or not applied Yes
configprops Display an all@ConfigurationPropertiesSet list of Yes
env Displays theConfigurableEnvironmentThe properties of the Yes
flyway Show the database migration path, if any Yes
health Display applicationHealth information(A simple ‘status’ is displayed when using an unauthenticated connection, and full details are displayed when using an authenticated connection) Yes
info Display arbitraryThe application of information Yes
liquibase Show any Liquibase database migration paths, if any Yes
metrics Show the current applicationmetricsinformation Yes
mappings Display an all@RequestMappingA set list of paths Yes
scheduledtasks Display application inSchedule a task Yes
sessions Enables retrieval and deletion of user sessions from the session store supported by Spring sessions. Not available when using the Spring Session support for reactive Web applications. Yes
shutdown Allows applications to be shut down gracefully (not enabled by default) No
threaddump Perform a thread dump Yes

The shutdown endpoint is off by default, so we can turn it on

# open shutdown endpoint management. The endpoint. Shutdown. Enabled = trueCopy the code

Shutdown only supports post submissions. You can either use POSTMAN or use the tools provided in IDEA.

If you are using a Web application (Spring MVC, Spring WebFlux, or Jersey), you can also use the following endpoints:

ID describe Enabled by default
heapdump Return a GZip compressedhprofHeap dump file Yes
jolokia Exposed over HTTPJMX beans(WebFlux is not available when Jolokia is on the classpath) Yes
logfile returnLog File ContentsHTTP is supported (if the logging.file or logging.path property is set)RangeHeader receives partial information about the contents of the log file Yes
prometheus Displayed in a format that can be captured by the Prometheus servermetricsinformation Yes

Now that we’re looking at less health information, if we need to look at more detailed information, we can configure it as follows

# health Displays details
management.endpoint.health.show-details=always
Copy the code

Reaccess test

This allows health to monitor not only SpringBoot itself, but also other components, such as when we enable the Redis service.

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

Add the configuration information of Redis

# host information for Redis
spring.redis.host=192.168.100.120
Copy the code

Restart the service, see http://localhost:8080/actuator/health

3. Monitoring type

Introduce some important types of monitoring

3.1 the health

The health information of the system displayed, which is more discussed in the case above, will not be repeated.

3.2 the metrics

The Metrics endpoint is used to return important metrics for the current application, such as memory information, thread information, garbage collection information, etc. As follows:

Detailed description of each indicator:

The serial number parameter Parameters that Whether the monitoring Monitoring means Important degree
JVM
1 jvm.memory.max JVMMaximum memory
2 jvm.memory.committed JVMThe available memory is Display and monitor heap memory andMetaspace important
3 jvm.memory.used JVMHave used the memory is Display and monitor heap memory andMetaspace important
4 jvm.buffer.memory.used JVMThe buffer has used memory
5 jvm.buffer.count Current number of buffers
6 jvm.threads.daemon JVMNumber of daemon threads is The monitoring page is displayed
7 jvm.threads.live JVMNumber of currently active threads is The monitoring page is displayed. The alarm is generated when the monitoring threshold is reached important
8 jvm.threads.peak JVMPeak thread count is The monitoring page is displayed
9 jvm.classes.loaded loadingclasses
10 jvm.classes.unloaded Not loadedclasses
11 jvm.gc.memory.allocated GC, the memory space allocated by the young generation
12 jvm.gc.memory.promoted GCWhen, the memory space allocated by the old age
13 jvm.gc.max.data.size GCWhen, the maximum memory space of the old age
14 jvm.gc.live.data.size FullGCWhen the old age memory space
15 jvm.gc.pause GCTime consuming is The monitoring page is displayed
TOMCAT
16 tomcat.sessions.created tomcatHas been createdsession
17 tomcat.sessions.expired tomcatexpiredsession
18 tomcat.sessions.active.current tomcatactivesession
19 tomcat.sessions.active.max tomcatThe most activesession is If the value exceeds the threshold, an alarm is generated or dynamic capacity expansion is performed important
20 tomcat.sessions.alive.max.second tomcatThe most activesessionNumber duration
21 tomcat.sessions.rejected More thansessionRejected after the maximum configurationsessionThe number of is The monitoring page is displayed, facilitating problem analysis
22 tomcat.global.error The total number of errors is The monitoring page is displayed, facilitating problem analysis
23 tomcat.global.sent Number of bytes sent
24 tomcat.global.request.max requestThe longest time
25 tomcat.global.request globalrequestFrequency and time
26 tomcat.global.received globalreceivedFrequency and time
27 tomcat.servlet.request servletThe number and time of requests
28 tomcat.servlet.error servletTotal number of errors
29 tomcat.servlet.request.max servletMaximum request time
30 tomcat.threads.busy tomcatBusy threads is Displays on the monitor page to check if a thread is jammed
31 tomcat.threads.current tomcatCurrent number of threads (including daemons) is The monitoring page is displayed important
32 tomcat.threads.config.max tomcatMaximum number of threads to be configured is The monitoring page is displayed important
33 tomcat.cache.access tomcatCache read times
34 tomcat.cache.hit tomcatCache hits
CPU
35 system.cpu.count CPUThe number of
36 system.load.average.1m load average is Alarm is generated when the threshold is exceeded important
37 system.cpu.usage systemCPUusage
38 process.cpu.usage The current processCPUusage is Alarm is generated when the threshold is exceeded
39 http.server.requests httpRequest invocation is According to10The number of requests is the largest and takes the longest timeURL; Statistics a200The amount of the request important
40 process.uptime The application has run time is The monitoring page is displayed
41 process.files.max Maximum number of handles allowed is Used with the number of currently open handles
42 process.start.time Application startup time is The monitoring page is displayed
43 process.files.open Number of currently open handles is The file handle usage exceeds the threshold important

To view the specific measurement information, add the measurement information directly after the access address:

http://localhost:8080/actuator/metrics/jvm.buffer.memory.used
Copy the code

Example Add a user-defined statistical indicator

In addition to using the metrics that the Metrics endpoint defaults to, you can also customize metrics. Metrics provides four basic metrics types:

  • Gauge gauges, the simplest type of metric, have a simple return value that is used to record the instantaneous value of some object or thing.
  • A Counter is an increment-only Counter. It is usually used to record the number of service requests, the number of tasks completed, and the number of errors
  • A Timer can measure both the call (execution) speed of a particular block of code logic and its time distribution. In simple terms, it records the total time of execution of the entire call block at the point in time when the call ends, and is suitable for measuring the time distribution of events that execute for short periods of time, such as the consumption rate of message queue messages.
  • Summary Summary is used to track the distribution of events. It is similar to a timer, but more generally, its size is not necessarily a measurement over time. In MicroMeter, the corresponding class is DistributionSummary, which is used somewhat like a Timer, except that the recorded value needs to be specified directly rather than by measuring the execution time of a task.

Testing:

@RestController
public class UserController {

    static final Counter userCounter = Metrics.counter("user.counter.total"."services"."bobo");
    private Timer timer = Metrics.timer("user.test.timer"."timer"."timersample");
    private DistributionSummary summary = Metrics.summary("user.test.summary"."summary"."summarysample");

    @GetMapping("/hello")
    public String hello(a){
        // Gauge
        Metrics.gauge("user.test.gauge".8);
        // Counter
        userCounter.increment(1);
        // timer
        timer.record(()->{
            try {
                Thread.sleep(3000);
            } catch(InterruptedException e) { e.printStackTrace(); }}); summary.record(2);
        summary.record(3);
        summary.record(4);
        return "Hello"; }}Copy the code

After watching the metrics information visit http://localhost:8080/hello this request

Extra metrics that we can customize.

3.3 loggers

Loggers are used to view log levels for each package in the current project.

The default is info.

Change the log level:

Send a POST request to http://localhost:8080/actuator/loggers/ [package path]

The request parameter is

{
    "configuredLevel":"DEBUG"
}
Copy the code

Send messages via POSTMAN

Then look at the log level and see that it has changed

You can also see it on the console

3.4 the info

Display any application information. We can define this in properties

Visit: http://localhost:8080/actuator/info

4. Customize an Endpoint

If we need to extend the Endpoint, we can customize the implementation by defining the following annotation in the header of the class

@Endpoint @WebEndpoint @ControllerEndpoint @RestControllerEndpoint @ServletEndpoint

Add an @ReadOperation, @WritOperation, or @DeleteOperation annotation to the method, and the method will be exposed automatically through JMX, and also through HTTP in the Web application.

There are three types of annotations for methods, one for GET, post and delete requests

Operation HTTP method
@ReadOperation GET
@WriteOperation POST
@DeleteOperation DELETE

Case study:

/** * Custom Endpoint */
@Component
@Endpoint(id = "sessions")
public class MyHealthEndPoint  {

    / * * *@SelectorGets the passed parameter */
    @ReadOperation
    public Info get(@Selector String name){
        return new Info(name,"18"); }}Copy the code

5. Two monitoring modes of the Actuator

  • http
  • JMX [Java Management Extensions] Java Management Extensions

Let go of JMX

Release the JMX endpoint
management.endpoints.jmx.exposure.include=*
spring.jmx.enabled=true
Copy the code

To view this, use the JConsole provided with the JDK

6. Monitoring system

SpringBoot can collect monitoring data, but viewing it is not very convenient. In this case, we can choose an open source monitoring system, such as Prometheus

  • The data collection
  • Data is stored
  • visualization

Prometheus is not very good in terms of visualization and can be achieved using Grafana

6.1 Prometheus

Install Prometheus: Prometheus. IO /download/ wget command to download Prometheus

Wget HTTP: / / https://github.com/prometheus/prometheus/releases/download/v2.28.1/prometheus-2.28.1.linux-amd64.tar.gzCopy the code

Then configure Prometheus.

  - job_name: 'Prometheus'
    static_configs:
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    - targets: ['192.168.127.1:8080']
      labels:
        instance: Prometheus

Copy the code
  • Job_name: indicates the task name
  • Metrics_path: indicates the indicator path
  • Targets: instance address/project address. Multiple targets can be configured
  • Scrape_interval: how often to collect
  • Scrape_timeout: indicates the acquisition timeout period

Run the script to start the application

./prometheus --config.file=prometheus.yml
Copy the code

Access the application: http://ip:9090

We then add the endpoints for Prometheus to our SpringBoot service, first adding the necessary dependencies

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

The endpoint information will then be available

The Prometheus server can periodically crawl this endpoint to obtain metrics data, which can then be seen

6.2 Grafana

Visual tools: grafana.com/grafana/dow…

Use the wget command to download the file

Wget https://dl.grafana.com/oss/release/grafana-8.0.6-1.x86_64.rpm sudo yum install grafana 8.0.6-1. X86_64. RPMCopy the code

Start the command

sudo service grafana-server start
sudo service grafana-server status
Copy the code

The login address is http://ip:3000. Default password admin/admin

Log in after the page

Add data source:

Add Dashboards grafana.com/grafana/das… Search for SpringBoot Dashboards

Find the Dashboards ID

And then I can import it

Click Load to display the following screen

Then you can see the corresponding monitoring data

That’s all for the related content of the Actuator!!