使用SpringBoot Actuator监控应用

使用SpringBootActuator监控应用

微服务的特点决定了功能模块的部署是分布式的,大部分功能模块都是运行在不同的机器上,彼此通过服务调用进

行交互,前后台的业务流会经过很多个微服务的处理和传递,出现了异常如何快速定位是哪个环节出现了问题?

在这种框架下,微服务的监控显得尤为重要。本文主要结合 Spring Boot Actuator,跟大家一起分享微服务

Spring Boot Actuator 的常见用法,方便我们在日常中对我们的微服务进行监控治理。

1、Actuator 监控

Spring Boot 使用“习惯优于配置的理念”,采用包扫描和自动化配置的机制来加载依赖 Jar 中的 Spring bean,不

需要任何 Xml 配置,就可以实现 Spring 的所有配置。虽然这样做能让我们的代码变得非常简洁,但是整个应用的

实例创建和依赖关系等信息都被离散到了各个配置类的注解上,这使得我们分析整个应用中资源和实例的各种关系

变得非常的困难。

Actuator 是 Spring Boot 提供的对应用系统的自省和监控的集成功能,可以查看应用配置的详细信息,例如自动

化配置信息、创建的 Spring beans 以及一些环境属性等。

为了保证 actuator 暴露的监控接口的安全性,需要添加安全控制的依赖spring-boot-start-security依赖,访

问应用监控端点时,都需要输入验证信息。Security 依赖,可以选择不加,不进行安全管理,但不建议这么做。

2、Actuator 的 REST 接口

Actuator 监控分成两类:原生端点和用户自定义端点;自定义端点主要是指扩展性,用户可以根据自己的实际应

用,定义一些比较关心的指标,在运行期进行监控。

原生端点是在应用程序里提供众多 Web 接口,通过它们了解应用程序运行时的内部状况。原生端点又可以分成三

类:

  • 应用配置类:可以查看应用在运行期的静态信息:例如自动配置信息、加载的 springbean 信息、yml 文件配

    置信息、环境信息、请求映射信息;

  • 度量指标类:主要是运行期的动态信息,例如堆栈、请求连、一些健康指标、metrics 信息等;

  • 操作控制类:主要是指 shutdown,用户可以发送一个请求将应用的监控功能关闭。

Actuator 提供了 13 个接口,具体如下表所示。

HTTP 方法路径描述
GET/auditevents显示应用暴露的审计事件 (比如认证进入、订单失败)
GET/beans描述应用程序上下文里全部的 Bean,以及它们的关系
GET/conditions就是 1.0 的 /autoconfig ,提供一份自动配置生效的条件情况,记录哪些自动配置条件通过了,哪些没通过
GET/configprops描述配置属性(包含默认值)如何注入Bean
GET/env获取全部环境属性
GET/env/{name}根据名称获取特定的环境属性值
GET/flyway提供一份 Flyway 数据库迁移信息
GET/liquidbase显示Liquibase 数据库迁移的纤细信息
GET/health报告应用程序的健康指标,这些值由 HealthIndicator 的实现类提供
GET/heapdumpdump 一份应用的 JVM 堆信息
GET/httptrace显示HTTP足迹,最近100个HTTP request/repsponse
GET/info获取应用程序的定制信息,这些信息由info打头的属性提供
GET/logfile返回log file中的内容(如果 logging.file 或者 logging.path 被设置)
GET/loggers显示和修改配置的loggers
GET/metrics报告各种应用程序度量信息,比如内存用量和HTTP请求计数
GET/metrics/{name}报告指定名称的应用程序度量值
GET/scheduledtasks展示应用中的定时任务信息
GET/sessions如果我们使用了 Spring Session 展示应用中的 HTTP sessions 信息
POST/shutdown关闭应用程序,要求endpoints.shutdown.enabled设置为true
GET/mappings描述全部的 URI路径,以及它们和控制器(包含Actuator端点)的映射关系
GET/threaddump获取线程活动的快照

3、快速上手

3.1 pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.6.RELEASE</version><relativePath/></parent><groupId>com.example</groupId><artifactId>spring-boot-actuator</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-actuator</name><description>spring-boot-actuator</description><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><fork>true</fork></configuration></plugin></plugins></build></project>

3.2 配置文件

info.app.name=spring-boot-actuator
info.app.version=1.0.0
info.app.test=testmanagement.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always# management.endpoints.web.base-path=/managemanagement.endpoint.shutdown.enabled=true
  • management.endpoints.web.base-path=/manage 代表启用单独的url地址来监控 Spring Boot 应用,为

    了安全一般都启用独立的端口来访问后端的监控信息。

  • management.endpoint.shutdown.enabled=true 启用接口关闭 Spring Boot

3.3 控制器

package com.example.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@RequestMapping("/hello")public String index() {return "Hello World";}
}

3.4 启动类

package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

配置完成之后,启动项目就可以继续验证各个监控功能了。

4、命令详解

在 Spring Boot 2.x 中为了安全期间,Actuator 只开放了两个端点 /actuator/health/actuator/info。可

以在配置文件中设置打开。

可以打开所有的监控点

management.endpoints.web.exposure.include=*

也可以选择打开部分

management.endpoints.web.exposure.exclude=beans,trace

Actuator 默认所有的监控点路径都在/actuator/*,当然如果有需要这个路径也支持定制。

management.endpoints.web.base-path=/manage

设置完重启后,再次访问地址就会变成/manage/*

Actuator 几乎监控了应用涉及的方方面面,我们重点讲述一些经常在项目中常用的命令。

4.1 health

health 主要用来检查应用的运行状态,这是我们使用最高频的一个监控点。通常使用此接口提醒我们应用实例的

运行状态,以及应用不”健康“的原因,比如数据库连接、磁盘空间不够等。

默认情况下 health 的状态是开放的,添加依赖后启动项目,访问:http://localhost:8080/actuator/health

即可看到应用的状态。

{"status": "UP","details": {"diskSpace": {"status": "UP","details": {"total": 22175952896,"free": 2316570624,"threshold": 10485760}}}
}

默认情况下,最终的 Spring Boot 应用的状态是由 HealthAggregator 汇总而成的,汇总的算法是:

  • 1 设置状态码顺序:setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);

  • 2 过滤掉不能识别的状态码。

  • 3 如果无任何状态码,整个 Spring Boot 应用的状态是 UNKNOWN。

  • 4 将所有收集到的状态码按照 1 中的顺序排序。

  • 5 返回有序状态码序列中的第一个状态码,作为整个 Spring Boot 应用的状态。

health 通过合并几个健康指数检查应用的健康情况。Spring Boot Actuator 有几个预定义的健康指标比如

DataSourceHealthIndicator, DiskSpaceHealthIndicator, MongoHealthIndicator,

RedisHealthIndicator等,它使用这些健康指标作为健康检查的一部分。

举个例子,如果你的应用使用 Redis,RedisHealthindicator 将被当作检查的一部分;如果使用 MongoDB,

那么MongoHealthIndicator 将被当作检查的一部分。

可以在配置文件中关闭特定的健康检查指标,比如关闭 redis 的健康检查:

management.health.redise.enabled=false

默认,所有的这些健康指标被当作健康检查的一部分。

4.2 info

info 就是我们自己配置在配置文件中以 info 开头的配置信息,比如我们在示例项目中的配置是:

info.app.name=spring-boot-actuator
info.app.version= 1.0.0
info.app.test= test

启动示例项目,访问:http://localhost:8080/actuator/info返回部分信息如下:

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

4.3 beans

根据示例就可以看出,展示了 bean 的别名、类型、是否单例、类的地址、依赖等信息。

启动示例项目,访问:http://localhost:8080/actuator/beans返回部分信息如下:

[{"context": "application:8080:management","parent": "application:8080","beans": [{"bean": "embeddedServletContainerFactory","aliases": [],"scope": "singleton","type": "org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory","resource": "null","dependencies": []},{"bean": "endpointWebMvcChildContextConfiguration","aliases": [],"scope": "singleton","type": "org.springframework.boot.actuate.autoconfigure.EndpointWebMvcChildContextConfiguration$$EnhancerBySpringCGLIB$$a4a10f9d","resource": "null","dependencies": []}}
]

4.4 conditions

Spring Boot 的自动配置功能非常便利,但有时候也意味着出问题比较难找出具体的原因。使用 conditions 可以

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

启动示例项目,访问:http://localhost:8080/actuator/conditions返回部分信息如下:

{"positiveMatches": {"DevToolsDataSourceAutoConfiguration": {"notMatched": [{"condition": "DevToolsDataSourceAutoConfiguration.DevToolsDataSourceCondition", "message": "DevTools DataSource Condition did not find a single DataSource bean"}], "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"}]}}
}

4.5 heapdump

返回一个 GZip 压缩的 JVM 堆 dump

启动示例项目,访问:http://localhost:8080/actuator/heapdump会自动生成一个 Jvm 的堆文件

heapdump,我们可以使用 JDK 自带的 Jvm 监控工具 VisualVM 打开此文件查看内存快照。

类似如下图:

在这里插入图片描述

4.6 shutdown

开启接口优雅关闭 Spring Boot 应用,要使用这个功能首先需要在配置文件中开启:

management.endpoint.shutdown.enabled=true

配置完成之后,启动示例项目,使用 curl 模拟 post 请求访问 shutdown 接口。

shutdown 接口默认只支持 post 请求。

curl -X POST "http://localhost:8080/actuator/shutdown" 
{"message": "Shutting down, bye..."
}

此时你会发现应用已经被关闭。

4.7 mappings

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

启动示例项目,访问:http://localhost:8080/actuator/mappings返回部分信息如下:

{"/**/favicon.ico": {"bean": "faviconHandlerMapping"},"{[/hello]}": {"bean": "requestMappingHandlerMapping","method": "public java.lang.String com.neo.controller.HelloController.index()"},"{[/error]}": {"bean": "requestMappingHandlerMapping","method": "public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)"}
}

4.8 threaddump

/threaddump 接口会生成当前线程活动的快照。这个功能非常好,方便我们在日常定位问题的时候查看线程的情

况。 主要展示了线程名、线程ID、线程的状态、是否等待锁资源等信息。

启动示例项目,访问:http://localhost:8080/actuator/threaddump返回部分信息如下:

[{"threadName": "http-nio-8088-exec-6","threadId": 49,"blockedTime": -1,"blockedCount": 0,"waitedTime": -1,"waitedCount": 2,"lockName": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@1630a501","lockOwnerId": -1,"lockOwnerName": null,"inNative": false,"suspended": false,"threadState": "WAITING","stackTrace": [{"methodName": "park","fileName": "Unsafe.java","lineNumber": -2,"className": "sun.misc.Unsafe","nativeMethod": true},...{"methodName": "run","fileName": "TaskThread.java","lineNumber": 61,"className": "org.apache.tomcat.util.threads.TaskThread$WrappingRunnable","nativeMethod": false}...],"lockInfo": {"className": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject","identityHashCode": 372286721}}...
]

生产出现问题的时候,可以通过应用的线程快照来检测应用正在执行的任务。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/192202.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Windows上搭建一个网站(基本生产环境)

前言 本博客记录的是Windows上一次网站搭建的过程&#xff0c;主要是在前端采用的是React&#xff0c;后端采用的是Flask&#xff0c;记录一下生产版本搭建流程和坑点&#xff0c;供有缘人一起进步&#xff0c;当然本博客还存在很多不足。 前端项目构建生产版本 以React为例…

【原创】java+swing+mysql鲜花购物商城设计与实现

前言&#xff1a; 本文主要介绍了鲜花购物商城的设计与实现。首先&#xff0c;通过市场需求&#xff0c;我们确定了鲜花商场的功能&#xff0c;通常的商城一般都是B/S架构&#xff0c;然而我们今天要用javaswing去开发一个C/S架构的鲜花商城&#xff0c;利用开发技术和工具&am…

C 语言多维数组

C 语言多维数组 在本教程中&#xff0c;您将借助示例学习使用多维数组&#xff08;二维和三维数组&#xff09;。 在C语言编程中&#xff0c;您可以创建一个数组数组。这些数组称为多维数组。例如&#xff0c; float x[3][4];这x是二维&#xff08;2d&#xff09;数组。该数…

[Vue3] pinia状态管理

文章目录 1.pinia的介绍2.pinia的配置3.state状态管理3.1 state的基本使用3.2 state的访问 4.getters 1.pinia的介绍 Pinia 是 Vue 的专属状态管理库&#xff0c;它允许你跨组件或页面共享状态。如果你熟悉组合式 API 的话&#xff0c;你可能会认为可以通过一行简单的 export …

SQL注入1

对sql进行一个小结 还有其他的注入 其他注入:堆叠注入&#xff0c;宽字节注入&#xff0c;二次注入 首先是数值和字符 id1 and 11和id1 and 12 如果这两个语句返回的页面不一样就说明是数字型 id1 and 11#和id1 and 12# 如果这两个语句返回的页面不一样就说明是字符型 常…

Matlab群体智能优化算法之海象优化算法(WO)

文章目录 一、灵感来源二、算法的初始化三、GTO的数学模型Phase1&#xff1a;危险信号和安全信号Phase2&#xff1a;迁移&#xff08;探索&#xff09;Phase3&#xff1a;繁殖&#xff08;开发&#xff09; 四、流程图五、伪代码六、算法复杂度七、WO搜索示意图八、实验分析和结…

MFC 对话框

目录 一、对话款基本认识 二、对话框项目创建 三、控件操作 四、对话框创建和显示 模态对话框 非模态对话框 五、动态创建按钮 六、访问控件 控件添加控制变量 访问对话框 操作对话框 SendMessage() 七、对话框伸缩功能实现 八、对话框小项目-逃跑按钮 九、小项…

Javaweb之Vue指令案例的详细解析

2.3.5 案例 需求&#xff1a; 如上图所示&#xff0c;我们提供好了数据模型&#xff0c;users是数组集合&#xff0c;提供了多个用户信息。然后我们需要将数据以表格的形式&#xff0c;展示到页面上&#xff0c;其中&#xff0c;性别需要转换成中文男女&#xff0c;等级需要…

jbase打印导出实现

上一篇实现了虚拟M层&#xff0c;这篇基于虚拟M实现打印导出。 首先对接打印层 using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Xml;namesp…

CorelDRAW2024最新版本的图形设计软件

CorelDRAW2024是Corel公司推出的最新版本的图形设计软件。CorelDRAW是一款功能强大的矢量图形编辑工具&#xff0c;被广泛用于图形设计、插图、页面布局、照片编辑和网页设计等领域。 1. 新增的设计工具&#xff1a;CorelDRAW 2024引入了一些全新的设计工具&#xff0c;使用户能…

LabVIEW和NIUSRP硬件加快了认知无线电开发

LabVIEW和NIUSRP硬件加快了认知无线电开发 对于电视频谱&#xff0c;主用户传输有两种类型&#xff1a;广播电视和节目制作和特殊事件(PMSE)设备。广播塔的位置已知&#xff0c;且覆盖电视传输塔&#xff08;复用器&#xff09;附近的某个特定地理区域&#xff08;称为排除区域…

cesium雷达扫描(雷达扫描线)

cesium雷达扫描(雷达扫描线) 下面富有源码 实现思路 使用ellipse方法加载圆型,修改ellipse中‘material’方法重写glsl来实现当前效果 示例代码 index.html <!DOCTYPE html> <html lang="en"><head>