Spring Boot (IX): Micro Application Monitoring Service Spring Boot Actuator Comments

1 Introduction

In the current micro-service architecture approach, we have a lot of services deployed on different machines, interacting with each other by way of a service call, the middle of a complete business process will go through a number of micro-processing and transmission services, then how to know the health status of each service is particularly important.

Luckily Spring Boot provides us with a monitoring module Spring Boot Actuator, this article will share with you to explore some of the Spring Boot Actuator some common usage to help us in our service to monitor micro-management in daily use.

Spring Boot Actuator help us realize the operation of the internal monitoring procedures, such as monitoring the situation, Bean loading conditions, environment variables, log information, thread information.

2. Actuator use of

2.1 Project relies

Use Spring Boot Actuator need to add the following dependency:

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

Note: due to the Spring Boot Actuator expose details of our services, in order to protect security, we recommend adding security controls related to dependence spring-boot-starter-security, so, when accessing application monitoring endpoints, you are required to enter authentication information. Required dependency as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.2 Project Configuration

Profile application.yml as follows:

Listing: the Spring-the Boot-Actuator / src / main / Resources / application.yml
***

server:
  port: 8080
info:
  app:
    name: spring-boot-actuator
    version: 1.0.0
spring:
  security:
    user:
      name: admin
      password: admin

Now to start the project, open the browser to access: http: // localhost: 8080 / actuator, you can see the page shown below json:

{
  "_links":{
    "self":{
      "href":"http://localhost:8080/actuator",
      "templated":false
    },
    "health":{
      "href":"http://localhost:8080/actuator/health",
      "templated":false
    },
    "health-component-instance":{
      "href":"http://localhost:8080/actuator/health/{component}/{instance}",
      "templated":true
    },
    "health-component":{
      "href":"http://localhost:8080/actuator/health/{component}",
      "templated":true
    },
    "info":{
      "href":"http://localhost:8080/actuator/info",
      "templated":false
    }
  }
}

These links are supported by default, only:

/actuator
/actuator/health
/health/{component}/{instance}
/health/{component}
/actuator/info

We can increase the allocation in the configuration file to open in application.yml more monitoring information:

management:
  endpoints:
    web:
      exposure:
        include: '*'
#      base-path: /monitor
  endpoint:
    health:
      show-details: always
    shutdown:
      enabled: true
  • management.endpoints.web.exposure.include='*'Opened on behalf of all the monitoring, of course, you can also be configured to be opened to monitor, such as: management.endpoints.web.exposure.include=beans,trace.
  • management.endpoint.health.show-details=alwaysMeaning health endpoint is on display all the details. By default, / actuator / health is disclosed, and does not show details.
  • management.endpoints.web.base-path=/monitorRepresentatives enable separate url address to monitor the Spring Boot application, the default path /actuator/*, if this open configuration, access path will become again after the restart /manage/*.
  • management.endpoint.shutdown.enabled=true Enabled interface goes down Spring Boot.

In some business scenarios, we may need to cross monitoring information acquisition, Spring Boot Actuator provides relevant CORS configuration to support cross-domain calls, by default, CORS support is disabled, only set management.endpoints.web.cors.allowed-originsthe property to enabled. The following configuration allows from the https://www.geekdigging.comGET and POST calls domains:

management:
  endpoints:
    web:
      cors:
        allowed-origins: https://www.geekdigging.com
        allowed-methods: GET,POST

2.3 REST Interface

Spring Boot Actuator provides us with a very rich monitoring interface, you can understand the internal state of the application is running through them. Meanwhile Actuator supports user-defined add endpoint, the user can monitor the operation of their practical application, to define some indicators are more concerned in accordance with.

HTTP method path description
GET /auditevents Displays the current audit events in the application of information
GET /beans Display a complete list of all the applications of Spring Beans
GET /conditions Status display configuration and autoconfiguration class category (configuration and auto-configuration classes) and their reasons are applied or not applied
GET /configprops Display a set list of all @ConfigurationProperties
GET /env Spring of the display attribute from the ConfigurableEnvironment
GET /flyway Display database migration path, if any
GET /health Health information display applications (displays a simple 'status' when using a non-certified connection to access, use authenticated connections to access all the information details are displayed)
GET /info Display any application information
GET / Liquibase Liquibase display any database migration path, if any
GET /metrics Display metrics information about the current application
GET /mappings It displays a list of all the set path of @RequestMapping
GET /scheduledtasks Display applications scheduled tasks
GET /sessions Spring session to allow support from the session store and retrieve deleted (retrieval and deletion) user sessions. Not available when using the Spring Session of the reactive support Web applications.
POST /shutdown Allows applications to shut down in a graceful manner (not enabled by default)
GET /threaddump Perform a thread dump

If you use a web application (Spring MVC, Spring WebFlux, or Jersey), you can also use the following interfaces:

HTTP method path description
GET /heapdump Returns a GZip compressed hprof heap dump file
GET /jolokia Exposure via HTTP JMX beans (when the Jolokia classpath, WebFlux unavailable)
GET /logfile Back log file contents (or if logging.file logging.path property set), the receiving supports HTTP Range header part of the information contents of the log file
GET /prometheus Display metrics information can be grasped format server Prometheus

3. Detailed Interface

3.1 /health

health is mainly used to check the operation status of the application, which we use the highest frequency of a monitoring point. This interface is generally used to remind our application instances running state, and the reason is not "healthy" applications, such as database connections, disk space is not enough and so on.

By default, the state of health is open to start the project after adding a dependency, visit: http: // localhost: 8080 / actuator / health to see the status of the application.

{
    "status" : "UP"
}

By default, the final status of Spring Boot application is HealthAggregatora summary made, a summary of the algorithm is:

  1. Status code sequence is setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);provided: .
  2. Filtered unrecognizable status code.
  3. If no status code, the entire Spring Boot application state is UNKNOWN.
  4. All the collected state codes sorted in the order of 1.
  5. Returns the ordered state code sequences in a first status code, as the state of the entire Spring Boot application.

Health through the merger of several health health index for your application. Spring Boot Actuator will automatically configure the following:

name description
CassandraHealthIndicator Check whether the Cassandra database started.
CouchbaseHealthIndicator Check that Couchbase cluster is started.
DiskSpaceHealthIndicator Check for low disk space.
DataSourceHealthIndicator Check whether you can establish a connection DataSource.
ElasticsearchHealthIndicator Check that Elasticsearch cluster is started.
InfluxDbHealthIndicator Check that InfluxDB server is started.
JmsHealthIndicator Check the JMS broker is started.
MailHealthIndicator Check that the mail server is started.
MongoHealthIndicator Check whether the Mongo database has been started.
Neo4jHealthIndicator Check that Neo4j server is started.
RabbitHealthIndicator Check whether the Rabbit server is started.
RedisHealthIndicator Check the Redis server is started.
SolrHealthIndicator Check if Solr server is started.

You can be set management.health.defaults.enabledto disable all of their property.

3.2 /info

info info is the message that begins with our own configuration in the configuration file, as we configured in the example project:

info:
  app:
    name: spring-boot-actuator
    version: 1.0.0

Start project, open the browser to access: http://localhost:8080/actuator/infothe following results:

{
  "app":{
    "name":"spring-boot-actuator",
    "version":"1.0.0"
  }
}

3.3 /beans

Start project, open the browser to access: http://localhost:8080/actuator/beans, part of the results are as follows:

{
    "contexts": {
        "application": {
            "beans": {
                "endpointCachingOperationInvokerAdvisor": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor",
                    "resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]",
                    "dependencies": ["environment"]
                },
                "defaultServletHandlerMapping": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.springframework.web.servlet.HandlerMapping",
                    "resource": "class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]",
                    "dependencies": []
                },
            },
            "parentId": null
        }
    }
}

从中可以看到,这个接口展现了 bean 的别名、类型、是否单例、类的地址、依赖等信息。

3.4 /conditions

启动工程,打开浏览器访问: http://localhost:8080/actuator/conditions ,部分结果如下:

{
    "contexts": {
        "application": {
            "positiveMatches": {
                "AuditAutoConfiguration#auditListener": [{
                    "condition": "OnBeanCondition",
                    "message": "@ConditionalOnMissingBean (types: org.springframework.boot.actuate.audit.listener.AbstractAuditListener; SearchStrategy: all) did not find any beans"
                }],
                "AuditAutoConfiguration#authenticationAuditListener": [{
                    "condition": "OnClassCondition",
                    "message": "@ConditionalOnClass found required class 'org.springframework.security.authentication.event.AbstractAuthenticationEvent'"
                }, {
                    "condition": "OnBeanCondition",
                    "message": "@ConditionalOnMissingBean (types: org.springframework.boot.actuate.security.AbstractAuthenticationAuditListener; SearchStrategy: all) did not find any beans"
                }],
            },
        }
    }
}

是用这个接口可以看出应用运行时查看代码了某个配置在什么条件下生效,或者某个自动配置为什么没有生效。

3.5 /shutdown

这个接口首先需要在配置文件中配置开启此功能:

management.endpoint.shutdown.enabled=true

配置完成后,可以使用 curl 模拟 post 请求此接口:

curl -X POST "http://localhost:8080/actuator/shutdown"

显示结果为:

{
    "message": "Shutting down, bye..."
}

注意:示例工程添加了 spring-boot-starter-security ,直接使用 post 访问此接口会响应 401 ,表示无权限访问,如需测试此接口,请暂时先关闭 spring-boot-starter-security

这时可以看到我们启动的示例工程已经关闭了。

3.6 /mappings

描述全部的 URI 路径,以及它们和控制器的映射关系

启动工程,打开浏览器访问: http://localhost:8080/actuator/mappings ,部分结果如下:

{
  "handler": "Actuator web endpoint 'beans'",
  "predicate": "{GET /actuator/beans, produces [application/vnd.spring-boot.actuator.v2+json || application/json]}",
  "details": {
    "handlerMethod": {
      "className": "org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.OperationHandler",
      "name": "handle",
      "descriptor": "(Ljavax/servlet/http/HttpServletRequest;Ljava/util/Map;)Ljava/lang/Object;"
    },
    "requestMappingConditions": {
      "consumes": [],
      "headers": [],
      "methods": ["GET"],
      "params": [],
      "patterns": ["/actuator/beans"],
      "produces": [{
        "mediaType": "application/vnd.spring-boot.actuator.v2+json",
        "negated": false
      }, {
        "mediaType": "application/json",
        "negated": false
      }]
    }
  }
}

3.7 /threaddump

/threaddump 接口会生成当前线程活动的快照。这个功能非常好,方便我们在日常定位问题的时候查看线程的情况。 主要展示了线程名、线程ID、线程的状态、是否等待锁资源等信息。

启动工程,打开浏览器访问: http://localhost:8080/actuator/threaddump ,部分结果如下:

{
    "threads": [{
        "threadName": "Reference Handler",
        "threadId": 2,
        "blockedTime": -1,
        "blockedCount": 2,
        "waitedTime": -1,
        "waitedCount": 0,
        "lockName": null,
        "lockOwnerId": -1,
        "lockOwnerName": null,
        "daemon": true,
        "inNative": false,
        "suspended": false,
        "threadState": "RUNNABLE",
        "priority": 10,
        "stackTrace": [{
            "classLoaderName": null,
            "moduleName": "java.base",
            "moduleVersion": "11.0.4",
            "methodName": "waitForReferencePendingList",
            "fileName": "Reference.java",
            "lineNumber": -2,
            "className": "java.lang.ref.Reference",
            "nativeMethod": true
        }
  ...
  "lockedMonitors": [],
        "lockedSynchronizers": [{
            "className": "java.util.concurrent.locks.ReentrantLock$NonfairSync",
            "identityHashCode": 2060076420
        }],
        "lockInfo": null
  ...
  {
        "threadName": "DestroyJavaVM",
        "threadId": 42,
        "blockedTime": -1,
        "blockedCount": 0,
        "waitedTime": -1,
        "waitedCount": 0,
        "lockName": null,
        "lockOwnerId": -1,
        "lockOwnerName": null,
        "daemon": false,
        "inNative": false,
        "suspended": false,
        "threadState": "RUNNABLE",
        "priority": 5,
        "stackTrace": [],
        "lockedMonitors": [],
        "lockedSynchronizers": [],
        "lockInfo": null
    }]
}

4. 示例代码

示例代码-Github

示例代码-Gitee

5. 参考:

使用 Spring Boot Actuator 监控应用

Spring Boot 官方文档之 Actuator

Guess you like

Origin www.cnblogs.com/babycomeon/p/11639361.html