Spring Boot Actuator 2.0 使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot Actuator 2.0 使用相关的知识,希望对你有一定的参考价值。

参考技术A 最近使用 Spring Boot Actuator,发现网上的资料怎么配置都不好使,endpoint 只有默认的2个,可能是因为 Spring Boot 现在是2.0的原因,所以总结一下自己是如何解决的。
我使用的 Spring Boot 是2.0.1版本

pom.xml

由 console 可以看到,初始只有这2个和 Actuator 有关的 endpoint
访问 /actuator

在 application.properties 里添加

引入所有 endpoint
再次访问 /actuator

所有的 endpoint 都出来了
还有很多关于 Actuator 的配置
可以查看

这个文件,记住前缀不一样,要看你自己的电脑上地址。
举个例子
访问 /actuator/health

在 additional-spring-configuration-metadata.json 文件中搜索 health,找到

再次访问 /actuator/health

效果出来了。

图中使用的 Chrome 和 JSONView 插件。

Spring Boot Actuator [监控与管理]

这是一篇结合Spring Boot 2.X 介绍actuator[‘?ktjueit?] 入门的文档
官方文档: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/actuator-api/html/

1. 如何添加

只需要在原来的POM中添加如下maven依赖:

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

 

添加完毕后,在启动的时候你就会发现如下的日子输出:

2018-09-22 00:33:19.713  INFO 22802 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path ‘/actuator‘
2018-09-22 00:33:19.720  INFO 22802 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:33:19.721  INFO 22802 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:33:19.721  INFO 22802 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-09-22 00:33:19.750  INFO 22802 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729

  

我们会发现Actuator 帮我添加了3个API

  • /actuator
  • /actuator/health
  • /actuator/info

/actuator
概括actuator所有的API,templated -> 标示当前URL是否是一个模板

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

 

/actuator/health

{
    status: "UP"
}

 

/actuator/info

{ }

 

后两个API几乎没有什么属性返回,别急,等我们项目集成了更多的Spring Cloud 插件之后,里面就会有更多的属性了。

应该还会有人有疑问,为什么原生的监控插件怎么就返回这么几个API呀,其实这个只是默认配置,就像下图,默认的配置如下:

management.endpoints.web.exposure.include= ["health","info"]

如果想加载全部的API只需要将这个参数设置成 * 就行了

management.endpoints.web.exposure.include = *

技术分享图片?

这个时候我们再启动程序的时候就会看到下边这些输出:

2018-09-22 00:43:30.917  INFO 22845 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 14 endpoint(s) beneath base path ‘/actuator‘
2018-09-22 00:43:30.930  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/auditevents],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.931  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/beans],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.931  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.931  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/conditions],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.931  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/configprops],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.931  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/env],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.931  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/env/{toMatch}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.932  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.932  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/loggers/{name}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.932  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/loggers/{name}],methods=[POST],consumes=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.932  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/loggers],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.933  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/heapdump],methods=[GET],produces=[application/octet-stream]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.933  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/threaddump],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.933  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/metrics/{requiredMetricName}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.933  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/metrics],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.933  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/scheduledtasks],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.933  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/httptrace],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.934  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/mappings],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-09-22 00:43:30.934  INFO 22845 --- [  restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-09-22 00:43:30.979  INFO 22845 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup

  

/actuator
同时这个API也将增加新的成员

{
  "_links": {
    "self": {
      "href": "http://localhost:8080/actuator",
      "templated": false
    },
    "auditevents": {
      "href": "http://localhost:8080/actuator/auditevents",
      "templated": false
    },
    "beans": {
      "href": "http://localhost:8080/actuator/beans",
      "templated": false
    },
    "health": {
      "href": "http://localhost:8080/actuator/health",
      "templated": false
    },
    "conditions": {
      "href": "http://localhost:8080/actuator/conditions",
      "templated": false
    },
    "configprops": {
      "href": "http://localhost:8080/actuator/configprops",
      "templated": false
    },
    "env": {
      "href": "http://localhost:8080/actuator/env",
      "templated": false
    },
    "env-toMatch": {
      "href": "http://localhost:8080/actuator/env/{toMatch}",
      "templated": true
    },
    "info": {
      "href": "http://localhost:8080/actuator/info",
      "templated": false
    },
    "loggers-name": {
      "href": "http://localhost:8080/actuator/loggers/{name}",
      "templated": true
    },
    "loggers": {
      "href": "http://localhost:8080/actuator/loggers",
      "templated": false
    },
    "heapdump": {
      "href": "http://localhost:8080/actuator/heapdump",
      "templated": false
    },
    "threaddump": {
      "href": "http://localhost:8080/actuator/threaddump",
      "templated": false
    },
    "metrics-requiredMetricName": {
      "href": "http://localhost:8080/actuator/metrics/{requiredMetricName}",
      "templated": true
    },
    "metrics": {
      "href": "http://localhost:8080/actuator/metrics",
      "templated": false
    },
    "scheduledtasks": {
      "href": "http://localhost:8080/actuator/scheduledtasks",
      "templated": false
    },
    "httptrace": {
      "href": "http://localhost:8080/actuator/httptrace",
      "templated": false
    },
    "mappings": {
      "href": "http://localhost:8080/actuator/mappings",
      "templated": false
    }
  }
}

 

是不是感觉接口增加了好多,是不是突然感觉无从下手,不要捉急,下边我们就来细细道来这些接口的作用。

2. actuator 的原生端点(API)

全部的API(endpoints): https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

Actuator的原生API有很多,但是大体上可以分为以下三类,

  • 应用配置类:应用配置/环境变量/自动化配置等
  • 度量指标类:运行时监控到的指标,如内存,线程池,HTTP统计信息等
  • 操作控制类:如对应用关闭等操作类

2.1 应用类配置

2.1.1 http://localhost:8080/actuator/conditions

该端点用来获取应用的自动化配置报告,其中包括所有自动化配置的候选项。同时还列出了每个候选项自动化配置的各个先决条件是否满足。所以,该端点可以帮助我们方便的找到一些自动化配置为什么没有生效的具体原因。该报告内容将自动化配置内容分为三部分:

  • positiveMatches中返回的是条件匹配成功的自动化配置
  • negativeMatches中返回的是条件匹配不成功的自动化配置
  • unconditionalClasses

简化起见,我们每个部分返回两个节点,结构如下:

{
  "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.AuditEventRepositoryConfiguration": [
          {
            "condition": "OnBeanCondition",
            "message": "@ConditionalOnMissingBean (types: org.springframework.boot.actuate.audit.AuditEventRepository; SearchStrategy: all) did not find any beans"
          }
        ]
      },
      "negativeMatches": {
        "RabbitHealthIndicatorAutoConfiguration": {
          "notMatched": [
            {
              "condition": "OnClassCondition",
              "message": "@ConditionalOnClass did not find required class ‘org.springframework.amqp.rabbit.core.RabbitTemplate‘"
            }
          ],
          "matched": []
        },
        "RemoteDevToolsAutoConfiguration": {
          "notMatched": [
            {
              "condition": "OnPropertyCondition",
              "message": "@ConditionalOnProperty (spring.devtools.remote.secret) did not find property ‘secret‘"
            }
          ],
          "matched": [
            {
              "condition": "OnClassCondition",
              "message": "@ConditionalOnClass found required classes ‘javax.servlet.Filter‘, ‘org.springframework.http.server.ServerHttpRequest‘; @ConditionalOnMissingClass did not find unwanted class"
            }
          ]
        }
      },
      "unconditionalClasses": [
        "org.springframework.boot.actuate.autoconfigure.management.HeapDumpWebEndpointAutoConfiguration",
        "org.springframework.boot.actuate.autoconfigure.scheduling.ScheduledTasksEndpointAutoConfiguration"
      ]
    }
  }
}

 

2.1.2 http://localhost:8080/actuator/beans

该接口返回当前上下文中配置的所有的Bean,从返回的数据来看,包含以下属性:

  • 外层是Bean的名称
  • aliases: 别名
  • scope:Bean作用域
  • type:Bean的Java类型
  • resource:class文件的路径
  • dependencies:所依赖的其他Bean

接口返回信息如下:

{
  "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.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping",
          "resource": "class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]",
          "dependencies": []
        }
      },
      "parentId": null
    }
  }
}

 

2.1.3 http://localhost:8080/actuator/configprops

该接口用来返回应用中配置的属性和值,prefix代表前缀,如我们在前边配置的 management.endpoints.web.exposure.include = *

{
  "contexts": {
    "application": {
      "beans": {
        "management.trace.http-org.springframework.boot.actuate.autoconfigure.trace.http.HttpTraceProperties": {
          "prefix": "management.trace.http",
          "properties": {
            "include": [
              "TIME_TAKEN",
              "REQUEST_HEADERS",
              "RESPONSE_HEADERS",
              "COOKIE_HEADERS"
            ]
          }
        },
        "management.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties": {
          "prefix": "management.endpoints.web",
          "properties": {
            "pathMapping": {},
            "exposure": {
              "include": [
                "*"
              ],
              "exclude": []
            },
            "basePath": "/actuator"
          }
        }
      },
      "parentId": null
    }
  }
}

 

2.1.4 http://localhost:8080/actuator/env & http://localhost:8080/actuator/env/{toMatch}

该端点与/configprops不同,它用来获取应用所有可用的环境属性报告。包括:环境变量、JVM属性、应用的配置配置、命令行中的参数。从下面该端点返回的示例片段中,我们可以看到它不仅返回了应用的配置属性,还返回了系统属性、环境变量等丰富的配置信息,其中也包括了应用还没有没有使用的配置。所以它可以帮助我们方便地看到当前应用可以加载的配置信息,并配合@ConfigurationProperties注解将它们引入到我们的应用程序中来进行使用。另外,为了配置属性的安全,对于一些类似密码等敏感信息,该端点都会进行隐私保护,但是我们需要让属性名中包含:password、secret、key这些关键词,这样该端点在返回它们的时候会使用*来替代实际的属性值。

{
  "activeProfiles": [],
  "propertySources": [
    {
      "name": "server.ports",
      "properties": {
        "local.server.port": {
          "value": 8080
        }
      }
    },
    {
      "name": "servletContextInitParams",
      "properties": {}
    },
    {
      "name": "systemProperties",
      "properties": {
        "java.runtime.name": {
          "value": "Java(TM) SE Runtime Environment"
        },
        "java.runtime.version": {
          "value": "1.8.0_144-b01"
        }
      }
    },
    {
      "name": "systemEnvironment",
      "properties": {
        "PATH": {
          "value": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/opt/tomcat9/bi:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/eric/Documents/apps/mongodb.3/bin:/usr/local/opt/apache-maven-3.5/bin",
          "origin": "System Environment Property "PATH""
        }
      }
    },
    {
      "name": "applicationConfig: [classpath:/application.properties]",
      "properties": {
        "management.endpoints.web.exposure.include": {
          "value": "*",
          "origin": "class path resource [application.properties]:2:45"
        }
      }
    },
    {
      "name": "refresh",
      "properties": {
        "spring.mustache.cache": {
          "value": "false"
        }
      }
    }
  ]
}

 

ENV是返回所有的环境参数,如果执行查看其中一个的只需要在后边加上参数名称即可。如:
http://localhost:8080/actuator/env/local.server.port

{
  "property": {
    "source": "server.ports",
    "value": 8080
  },
  "activeProfiles": [],
  "propertySources": [
    {
      "name": "server.ports",
      "property": {
        "value": 8080
      }
    },
    {
      "name": "servletConfigInitParams"
    },
    {
      "name": "servletContextInitParams"
    },
    {
      "name": "systemProperties"
    },
    {
      "name": "systemEnvironment"
    },
    {
      "name": "random"
    },
    {
      "name": "applicationConfig: [classpath:/application.properties]"
    },
    {
      "name": "refresh"
    },
    {
      "name": "Management Server"
    }
  ]
}

 

2.1.5 http://localhost:8080/actuator/info

展示了关于应用的一般信息,这些信息从编译文件比如META-INF/build-info.properties或者Git文件比如git.properties或者任何环境的property中获取。

深度解析:https://blog.csdn.net/qq_26000415/article/details/79234812
使用案例: https://blog.csdn.net/dyc87112/article/details/73739530

2.1.6 http://localhost:8080/actuator/mappings

显示所有的@RequestMapping路径

{
  "contexts": {
    "application": {
      "mappings": {
        "dispatcherServlets": {
          "dispatcherServlet": [
            {
              "handler": "ResourceHttpRequestHandler [locations=[class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/], class path resource []], resolvers=[[email protected]fcd3bb]]",
              "predicate": "/**/favicon.ico",
              "details": null
            }
          ]
        },
        "servletFilters": [
          {
            "servletNameMappings": [],
            "urlPatternMappings": [
              "/*"
            ],
            "name": "webMvcMetricsFilter",
            "className": "org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter"
          }
        ],
        "servlets": [
          {
            "mappings": [
              "/"
            ],
            "name": "dispatcherServlet",
            "className": "org.springframework.web.servlet.DispatcherServlet"
          }
        ]
      },
      "parentId": null
    }
  }
}

 

2.2 度量指标类

2.2.1 http://localhost:8080/actuator/health

目前返回信息比较简单,UP 代表当前程序时启动状态。

{
    "status": "UP"
}

如果我们再配置文件中打开详细信息的显示,就会看到如下信息:

management.endpoint.health.show-details=always

{
  "status": "UP",
  "details": {
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 499963170816,
        "free": 294690533376,
        "threshold": 10485760
      }
    }
  }
}

 

这些是默认的信息,如果我们想客户这些信息我们可以:

  • 实现HealthIndicator
  • 继承AbstractHealthIndicator抽象类,重写doHealthCheck方法

当然我们依赖spring-boot-xxx-starter后,一些相关HealthIndicator的实现就会被自动装配,同样的相应的信息也会在这个API返回。

常见的HealthIndicator作用
CassandraHealthIndicator 检查 Cassandra 数据库是否启动
DiskSpaceHealthIndicator 检查磁盘空间不足
DataSourceHealthIndicator 检查是否可以获得连接 DataSource
ElasticsearchHealthIndicator 检查 Elasticsearch 集群是否启动
InfluxDbHealthIndicator 检查 InfluxDB 服务器是否启动
JmsHealthIndicator 检查 JMS 代理是否启动
MailHealthIndicator 检查邮件服务器是否启动
MongoHealthIndicator 检查 Mongo 数据库是否启动
Neo4jHealthIndicator 检查 Neo4j 服务器是否启动
RabbitHealthIndicator 检查 Rabbit 服务器是否启动
RedisHealthIndicator 检查 Redis 服务器是否启动
SolrHealthIndicator 检查 Solr 服务器是否已启动

2.2.2 http://localhost:8080/actuator/auditevents

显示应用暴露的审计事件 (比如认证进入、订单失败)

{
    "events": [ ]
}

 

2.2.3 http://localhost:8080/actuator/loggers & http://localhost:8080/actuator/loggers/{name}

显示和修改配置的loggers。它展示了应用中可配置的loggers的列表和相关的日志等级。

{
  "levels": [
    "OFF",
    "ERROR",
    "WARN",
    "INFO",
    "DEBUG",
    "TRACE"
  ],
  "loggers": {
    "ROOT": {
      "configuredLevel": "INFO",
      "effectiveLevel": "INFO"
    },
    "{name}": {
      "configuredLevel": null,
      "effectiveLevel": "INFO"
    }
  }
}

 

你同样能够使用 http://localhost:8080/actuator/loggers/{name} 来展示特定logger的细节。如你可以使用 http://localhost:8080/actuator/loggers/ROOT:

{
  "configuredLevel": "INFO",
  "effectiveLevel": "INFO"
}

/loggers 这个API不止可以查看Logger等级,还可以修改运行时Logger的等级。

如你可以用POST调用 http://localhost:8080/actuator/loggers/ROOT ,并传递如下参数:

{
   "configuredLevel": "DEBUG"
}

 

技术分享图片?

我们再回过头来查看ROOT的Loggers等级时,已经修改为如下状态:

{
    "configuredLevel": "DEBUG",
    "effectiveLevel": "DEBUG"
}

 

2.2.4 http://localhost:8080/actuator/metrics & http://localhost:8080/actuator/metrics/{requiredMetricName}

Metrics的可视化: https://bigjar.github.io/2018/08/19/Spring-Boot-Metrics%E7%9B%91%E6%8E%A7%E4%B9%8BPrometheus-Grafana/

这一对不像前边的几对API,这一对是前边的API返回所有你能查看的度量指标,后边是看某一个度量指标的具体值。

{
    "names": [
        "jvm.memory.max",
        "http.server.requests",
        "process.files.max",
        "jvm.gc.memory.promoted",
        "tomcat.cache.hit",
        "system.load.average.1m",
        "tomcat.cache.access",
        "jvm.memory.used",
        "jvm.gc.max.data.size",
        "jvm.gc.pause",
        "jvm.memory.committed",
        "system.cpu.count",
        "logback.events",
        "tomcat.global.sent",
        "jvm.buffer.memory.used",
        "tomcat.sessions.created",
        "jvm.threads.daemon",
        "system.cpu.usage",
        "jvm.gc.memory.allocated",
        "tomcat.global.request.max",
        "tomcat.global.request",
        "tomcat.sessions.expired",
        "jvm.threads.live",
        "jvm.threads.peak",
        "tomcat.global.received",
        "process.uptime",
        "tomcat.sessions.rejected",
        "process.cpu.usage",
        "tomcat.threads.config.max",
        "jvm.classes.loaded",
        "jvm.classes.unloaded",
        "tomcat.global.error",
        "tomcat.sessions.active.current",
        "tomcat.sessions.alive.max",
        "jvm.gc.live.data.size",
        "tomcat.servlet.request.max",
        "tomcat.threads.current",
        "tomcat.servlet.request",
        "process.files.open",
        "jvm.buffer.count",
        "jvm.buffer.total.capacity",
        "tomcat.sessions.active.max",
        "tomcat.threads.busy",
        "process.start.time",
        "tomcat.servlet.error"
    ]
}

 

如我们想 jvm.memory.max 具体的值,可以通过下边的URL查看
http://localhost:8080/actuator/metrics/jvm.memory.max

{
    "name": "jvm.memory.max",
    "description": "The maximum amount of memory in bytes that can be used for memory management",
    "baseUnit": "bytes",
    "measurements": [
        {
            "statistic": "VALUE",
            "value": 5602017279
        }
    ],
    "availableTags": [
        {
            "tag": "area",
            "values": [
                "heap",
                "nonheap"
            ]
        },
        {
            "tag": "id",
            "values": [
                "Compressed Class Space",
                "PS Survivor Space",
                "PS Old Gen",
                "Metaspace",
                "PS Eden Space",
                "Code Cache"
            ]
        }
    ]
}

 

2.2.5 http://localhost:8080/actuator/heapdump

返回一个GZip压缩的JVM堆dump

介绍HeapDumpWebEndpoint原理: https://www.jianshu.com/p/6df45fed02fa
分析dump文件: https://www.cnblogs.com/liangzs/p/8489321.html
分析dump文件: https://blog.csdn.net/albertfly/article/details/78686408
分析dump文件: https://www.javatang.com/archives/2017/10/30/53562102.html
分析dump文件: https://www.cnblogs.com/toSeeMyDream/p/7151635.html

2.2.6 http://localhost:8080/actuator/threaddump

执行一个线程dump

分析工具和方法: https://blog.csdn.net/hivon/article/details/8331350

{
  "threads": [
    {
      "threadName": "DestroyJavaVM",
      "threadId": 59,
      "blockedTime": -1,
      "blockedCount": 0,
      "waitedTime": -1,
      "waitedCount": 0,
      "lockName": null,
      "lockOwnerId": -1,
      "lockOwnerName": null,
      "inNative": false,
      "suspended": false,
      "threadState": "RUNNABLE",
      "stackTrace": [],
      "lockedMonitors": [],
      "lockedSynchronizers": [],
      "lockInfo": null
    }
  ]
}

 

2.2.7 http://localhost:8080/actuator/scheduledtasks

显示应用中的调度任务

{
    "cron": [],
    "fixedDelay": [],
    "fixedRate": []
}

 

2.2.8 http://localhost:8080/actuator/httptrace

显示HTTP足迹,最近100个HTTP request/repsponse

{
  "traces": [
    {
      "timestamp": "2018-09-23T05:45:34.642Z",
      "principal": null,
      "session": null,
      "request": {
        "method": "GET",
        "uri": "http://localhost:8080/actuator/scheduledtasks",
        "headers": {
          "postman-token": [
            "bf0a747f-a8dd-433e-90e6-17f869a75d15"
          ],
          "host": [
            "localhost:8080"
          ],
          "connection": [
            "keep-alive"
          ],
          "cache-control": [
            "no-cache"
          ],
          "accept-encoding": [
            "gzip, deflate"
          ],
          "accept": [
            "*/*"
          ],
          "user-agent": [
            "PostmanRuntime/7.3.0"
          ]
        },
        "remoteAddress": null
      },
      "response": {
        "status": 200,
        "headers": {
          "Transfer-Encoding": [
            "chunked"
          ],
          "Date": [
            "Sun, 23 Sep 2018 05:45:34 GMT"
          ],
          "Content-Type": [
            "application/vnd.spring-boot.actuator.v2+json;charset=UTF-8"
          ]
        }
      },
      "timeTaken": 14
    }
  ]
}

 

2.3 操作类

2.3.1 http://localhost:8080/actuator/shutdown

POST: /shutdown

默认是关闭的,可以通过下边的配置开启这个API:

management.endpoint.shutdown.enabled=true

技术分享图片?

3. Actuator 在 Spring Boot 1.X 和Spring Boot 2.X 的差异

Spring Boot 1.X Actuator 一些属性的介绍: http://357029540.iteye.com/blog/2392530

3.1 配置Key之间的变化

1.X 属性2.X 属性
endpoints.<id >.* management.endpoint.<id>.*
endpoints.cors.* management.endpoints.web.cors.*
endpoints.jmx.* management.endpoints.jmx.*
management.address management.server.address
management.context-path management.server.servlet.context-path
management.ssl.* management.server.ssl.*
management.port management.server.port

3.2 根节点发生了变化

2.X 比1.X 多了一个根路径: /actuator 。当然你也可以通过management.endpoints.web.base-path 设置一个根节点。如果你设置management.server.servlet.context-path=/managementmanagement.endpoints.web.base-path=/application,你就可以在下面的路径到达终点健康:/management/application/health 。注意context-path只有在设置了 management.server.port 时才有效。

3.3 一些端点发生变化(API)

  • /autoconfig -> 更名为 /conditions
  • /docs -> 被废弃
  • /health -> 有一个 management.endpoint.health.show-details 选项 never, always, when-authenticated,而不是依靠 sensitive 标志来确定 health 端点是否必须显示全部细节。 默认情况下,/actuator/health公开并且不显示细节。
  • /trace -> 更名为 /httptrace
  • /dump -> 更名为 /threaddump










以上是关于Spring Boot Actuator 2.0 使用的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 2.0 Actuator git 属性未添加到 /info

Spring boot 2.0 Actuator 的健康检查

关于spring boot启动监控端点的方法(spring-boot-starter-actuator)

Spring Boot 2.X(十六):应用监控之 Spring Boot Actuator 使用及配置

无法访问 Spring Boot Actuator“/actuator”端点

Spring Boot -- actuator