Spring Boot (九): 微服务应用监控 Spring Boot Actuator 详解
1. 引言
在当前的微服务架构方式下,我们会有很多的服务部署在不同的机器上,相互是通过服务调用的方式进行交互,一个完整的业务流程中间会经过很多个微服务的处理和传递,那么,如何能知道每个服务的健康状况就显得尤为重要。
万幸的是 Spring Boot 为我们提供了监控模块 Spring Boot Actuator ,本篇文章将和大家一起探讨一些 Spring Boot Actuator 一些常见用法方便我们在日常的使用中对我们的微服务进行监控治理。
Spring Boot Actuator 帮我们实现了对程序内部运行情况监控,比如监控状况、Bean加载情况、环境变量、日志信息、线程信息等。
2. Actuator 的使用
2.1 工程依赖
使用 Spring Boot Actuator 需要加入如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
注意: 因 Spring Boot Actuator 会暴露我们服务的详细信息,为了保障安全性,建议添加安全控制的相关依赖 spring-boot-starter-security
,这样,在访问应用监控端点时,都需要输入验证信息。所需依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.2 工程配置
配置文件 application.yml 如下:
代码清单:spring-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
现在先启动工程,打开浏览器访问:http://localhost:8080/actuator ,可以看到页面显示如下 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
}
}
}
这些是默认支持的链接,只有:
/actuator
/actuator/health
/health/{component}/{instance}
/health/{component}
/actuator/info
我们可以在配置文件 application.yml 中增加配置来开启更多的监控信息:
management:
endpoints:
web:
exposure:
include: '*'
# base-path: /monitor
endpoint:
health:
show-details: always
shutdown:
enabled: true
management.endpoints.web.exposure.include='*'
代表开启全部监控,当然也可以配置需要开启的监控,如:management.endpoints.web.exposure.include=beans,trace
。management.endpoint.health.show-details=always
含义是 health endpoint 是开启显示全部细节。默认情况下, /actuator/health 是公开的,并且不显示细节。management.endpoints.web.base-path=/monitor
代表启用单独的url地址来监控 Spring Boot 应用,默认的路径是/actuator/*
,如果开启此配置,重启后再次访问路径就会变成/manage/*
。management.endpoint.shutdown.enabled=true
启用接口关闭 Spring Boot 。
在某些业务场景下,我们的监控信息可能会需要跨越获取, Spring Boot Actuator 提供了 CORS 相关的配置,来支持跨域调用,默认情况下,CORS 支持处于禁用状态,只有在设置了 management.endpoints.web.cors.allowed-origins
属性后才能启用。以下配置允许来自 https://www.geekdigging.com
域的 GET 和 POST 调用:
management:
endpoints:
web:
cors:
allowed-origins: https://www.geekdigging.com
allowed-methods: GET,POST
2.3 REST 接口
Spring Boot Actuator 为我们提供了非常丰富的监控接口,可以通过它们了解应用程序运行时的内部状况。同时 Actuator 支持用户自定义添加端点,用户可以根据自己的实际应用,定义一些比较关心的指标,在运行期进行监控。
HTTP 方法 | 路径 | 描述 |
---|---|---|
GET | /auditevents | 显示当前应用程序的审计事件信息 |
GET | /beans | 显示一个应用中所有Spring Beans的完整列表 |
GET | /conditions | 显示配置类和自动配置类(configuration and auto-configuration classes)的状态及它们被应用或未被应用的原因 |
GET | /configprops | 显示一个所有@ConfigurationProperties的集合列表 |
GET | /env | 显示来自Spring的 ConfigurableEnvironment的属性 |
GET | /flyway | 显示数据库迁移路径,如果有的话 |
GET | /health | 显示应用的健康信息(当使用一个未认证连接访问时显示一个简单的’status’,使用认证连接访问则显示全部信息详情) |
GET | /info | 显示任意的应用信息 |
GET | /liquibase | 展示任何Liquibase数据库迁移路径,如果有的话 |
GET | /metrics | 展示当前应用的metrics信息 |
GET | /mappings | 显示一个所有@RequestMapping路径的集合列表 |
GET | /scheduledtasks | 显示应用程序中的计划任务 |
GET | /sessions | 允许从Spring会话支持的会话存储中检索和删除(retrieval and deletion)用户会话。使用Spring Session对反应性Web应用程序的支持时不可用。 |
POST | /shutdown | 允许应用以优雅的方式关闭(默认情况下不启用) |
GET | /threaddump | 执行一个线程dump |
如果使用web应用(Spring MVC, Spring WebFlux, 或者 Jersey),还可以使用以下接口:
HTTP 方法 | 路径 | 描述 |
---|---|---|
GET | /heapdump | 返回一个GZip压缩的hprof堆dump文件 |
GET | /jolokia | 通过HTTP暴露JMX beans(当Jolokia在类路径上时,WebFlux不可用) |
GET | /logfile | 返回日志文件内容(如果设置了logging.file或logging.path属性的话),支持使用HTTP Range头接收日志文件内容的部分信息 |
GET | /prometheus | 以可以被Prometheus服务器抓取的格式显示metrics信息 |
3. 接口详解
3.1 /health
health 主要用来检查应用的运行状态,这是我们使用最高频的一个监控点。通常使用此接口提醒我们应用实例的运行状态,以及应用不”健康“的原因,比如数据库连接、磁盘空间不够等。
默认情况下 health 的状态是开放的,添加依赖后启动项目,访问:http://localhost:8080/actuator/health 即可看到应用的状态。
{
"status" : "UP"
}
默认情况下,最终的 Spring Boot 应用的状态是由 HealthAggregator
汇总而成的,汇总的算法是:
- 设置状态码顺序:
setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);
。 - 过滤掉不能识别的状态码。
- 如果无任何状态码,整个 Spring Boot 应用的状态是 UNKNOWN。
- 将所有收集到的状态码按照 1 中的顺序排序。
- 返回有序状态码序列中的第一个状态码,作为整个 Spring Boot 应用的状态。
Health 通过合并几个健康指数检查应用的健康情况。Spring Boot Actuator 会自动配置以下内容:
名称 | 描述 |
---|---|
CassandraHealthIndicator | 检查Cassandra数据库是否已启动。 |
CouchbaseHealthIndicator | 检查Couchbase群集是否已启动。 |
DiskSpaceHealthIndicator | 检查磁盘空间不足。 |
DataSourceHealthIndicator | 检查是否可以建立连接 DataSource 。 |
ElasticsearchHealthIndicator | 检查Elasticsearch集群是否已启动。 |
InfluxDbHealthIndicator | 检查InfluxDB服务器是否已启动。 |
JmsHealthIndicator | 检查JMS代理是否启动。 |
MailHealthIndicator | 检查邮件服务器是否已启动。 |
MongoHealthIndicator | 检查Mongo数据库是否已启动。 |
Neo4jHealthIndicator | 检查Neo4j服务器是否已启动。 |
RabbitHealthIndicator | 检查Rabbit服务器是否已启动。 |
RedisHealthIndicator | 检查Redis服务器是否启动。 |
SolrHealthIndicator | 检查Solr服务器是否已启动。 |
可以通过设置 management.health.defaults.enabled
属性来全部禁用它们。
3.2 /info
info 就是我们自己在配置文件中配置的以 info 开头的信息,如我们在示例工程中配置的:
info:
app:
name: spring-boot-actuator
version: 1.0.0
启动工程,打开浏览器访问: http://localhost:8080/actuator/info
,结果如下:
{
"app":{
"name":"spring-boot-actuator",
"version":"1.0.0"
}
}
3.3 /beans
启动工程,打开浏览器访问: http://localhost:8080/actuator/beans
,部分结果如下:
{
"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. 示例代码
5. 参考:
Spring Boot (九): 微服务应用监控 Spring Boot Actuator 详解的更多相关文章
- Spring Cloud与微服务构建:Spring Cloud简介
Spring Cloud简介 微服务因该具备的功能 微服务可以拆分为"微"和"服务"二字."微"即小的意思,那到底多小才算"微&q ...
- 物联网架构成长之路(30)-Spring Boot Admin微服务WebUI监控
0. 前言 一个完整的微服务解决方案包含了许多微服务,基于我们需要观察各个微服务的运行状态,因此Spring Boot 生态提供了Spring Boot Admin 这个组件来实现微服务管理WEB U ...
- SpringCloud微服务项目实战 - API网关Gateway详解实现
前面讲过zuul的网关实现,那为什么今天又要讲Spring Cloud Gateway呢?原因很简单.就是Spring Cloud已经放弃Netflix Zuul了.现在Spring Cloud中引用 ...
- 【SpringCloud构建微服务系列】Feign的使用详解
一.简介 在微服务中,服务消费者需要请求服务生产者的接口进行消费,可以使用SpringBoot自带的RestTemplate或者HttpClient实现,但是都过于麻烦. 这时,就可以使用Feign了 ...
- 微服务 Zipkin 链路追踪原理(图文详解)
一个看起来很简单的应用,可能需要数十或数百个服务来支撑,一个请求就要多次服务调用. 当请求变慢.或者不能使用时,我们是不知道是哪个后台服务引起的. 这时,我们使用 Zipkin 就能解决这个问题. 由 ...
- 微服务架构:Eureka参数配置项详解
版权声明:本文为博主原创文章,转载请注明出处,欢迎交流学习! Eureka涉及到的参数配置项数量众多,它的很多功能都是通过参数配置来实现的,了解这些参数的含义有助于我们更好的应用Eureka的各种功能 ...
- 一文读懂 Spring Boot、微服务架构和大数据治理三者之间的故事
微服务架构 微服务的诞生并非偶然,它是在互联网高速发展,技术日新月异的变化以及传统架构无法适应快速变化等多重因素的推动下诞生的产物.互联网时代的产品通常有两类特点:需求变化快和用户群体庞大,在这种情况 ...
- Spring Boot、微服务架构和大数据
一文读懂 Spring Boot.微服务架构和大数据治理三者之间的故事 https://www.cnblogs.com/ityouknow/p/9034377.html 微服务架构 微服务的诞生并非偶 ...
- Spring Cloud搭建微服务架构----文章汇总
Spring Cloud搭建微服务架构----前言 原文地址:https://my.oschina.net/u/1000241/blog/882929 Spring Cloud搭建微服务架构----使 ...
随机推荐
- 复习+dfs
1.参考:https://www.cnblogs.com/ckxkexing/p/8466097.html 这道题自己写过,还写过blog,但是第二次写还是不会. (于是开坑,想做做dfs的整理.
- lightoj 1057 - Collecting Gold(状压dp)
题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1057 题解:看似有点下记忆话搜索但是由于他是能走8个方向的也就是说两点的距离其 ...
- 多级树的深度遍历与广度遍历(Java实现)
目录 多级树的深度遍历与广度遍历 节点模型 深度优先遍历 广度优先遍历 多级树的深度遍历与广度遍历 深度优先遍历与广度优先遍历其实是属于图算法的一种,多级树可以看做是一种特殊的图,所以多级数的深/广遍 ...
- 2、pytest中文文档--使用和调用
目录 使用和调用 通过python -m pytest调用pytest *pytest执行结束时返回的状态码 pytest命令执行结束,可能会返回以下六种状态码: *获取帮助信息 最多允许失败的测试用 ...
- 实现 Java 本地缓存,该从这几点开始
缓存,我相信大家对它一定不陌生,在项目中,缓存肯定是必不可少的.市面上有非常多的缓存工具,比如 Redis.Guava Cache 或者 EHcache.对于这些工具,我想大家肯定都非常熟悉,所以今天 ...
- Event Loop js 事件循环初理解
浏览器环境 执行栈 所有的 JS 代码在运行是都是在执行上下文中进行的.执行上下文是一个抽象的概念,JS 中有三种执行上下文: 全局执行上下文,默认的,在浏览器中是 window 对象 函数执行上下文 ...
- c语言文件的基本操作
c语言对文件的操作主要分为:按字符操作,按行操作,按内存块操作 主要的函数: fopen(): FILE * fopen(_In_z_ const char * _Filename, _In_z_ c ...
- 史上最全 69 道 Spring 面试题和答案
史上最全 69 道 Spring 面试题和答案 目录Spring 概述依赖注入Spring beansSpring注解Spring数据访问Spring面向切面编程(AOP)Spring MVC Spr ...
- 反射,Expression Tree,IL Emit 属性操作对比
.net的反射(Reflection) 是.Net中获取运行时类型信息的一种方法,通过反射编码的方式可以获得 程序集,模块,类型,元数据等信息. 反射的优点在于微软提供的API调用简单,使用方便: 表 ...
- Unity基础:AR(增强现实)的学习
版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...