SpringBoot3-12.可观测性

2024年01月08日 12:10 · 阅读(168) ·

描述

可观测性 Observability
对线上应用进行观测、监控、预警…
● 健康状况【组件状态、存活状态】Health
● 运行指标【cpu、内存、垃圾回收、吞吐量、响应成功率…】Metrics
● 链路追踪
● …

实战

新建项目-boot3-14-actuator

  • 新建模块 boot3-13-actuator

  • 创建模块

名称 boot3-14-actuator
位置 D:\Study-Java\2023\SpringBoot3-Study
语言 Java
类型 Maven
com.atguigu
工件 boot3-14-actuator
软件包名称 com.atguigu.boot3.actuator
JDK 版本:17
供应商:Eclipse Temurin(AdoptOpenJDK HotSpot)17.0.8
位置:C:\Users\Administrator.jdks\temurin-17.0.8
Java 17
  • SpringBoot 3.2.0
  • 依赖项目
  1. Developer Tools
  2. -- Lombok
  3. Web
  4. -- Spring Web
  5. Ops
  6. -- Spring Boot Actuator

场景引入

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>

暴露指标

  1. management:
  2. endpoints:
  3. enabled-by-default: true #暴露所有端点信息
  4. web:
  5. exposure:
  6. include: '*' #以web方式暴露

访问数据

● 访问
http://localhost:8080/actuator
http://localhost:8080/actuator/beans
http://localhost:8080/actuator/configprops
http://localhost:8080/actuator/metrics
http://localhost:8080/actuator/metrics/jvm.gc.pause
http://localhost:8080/actuator/endpointName/detailPath

Endpoint

1.常用端点

常用:threaddumpheapdumpmetrics

ID 描述
auditevents 暴露当前应用程序的审核事件信息。需要一个 AuditEventRepository 组件。
beans 显示应用程序中所有 Spring Bean 的完整列表。
caches 暴露可用的缓存。
conditions 显示自动配置的所有条件信息,包括匹配或不匹配的原因。
configprops 显示所有 @ConfigurationProperties
env 暴露 Spring 的属性 ConfigurableEnvironment
flyway 显示已应用的所有Flyway数据库迁移。
需要一个或多个 Flyway 组件。
health 显示应用程序运行状况信息。
httptrace 显示 HTTP 跟踪信息(默认情况下,最近 100 个 HTTP 请求-响应)。
需要一个 HttpTraceRepository 组件。
info 显示应用程序信息。
integrationgraph 显示 Spring integrationgraph 。
需要依赖 spring-integration-core
loggers 显示和修改应用程序中日志的配置。
liquibase 显示已应用的所有 Liquibase 数据库迁移。
需要一个或多个 Liquibase 组件。
metrics 显示当前应用程序的“指标”信息。
mappings 显示所有 @RequestMapping 路径列表。
scheduledtasks 显示应用程序中的计划任务。
sessions 允许从 Spring Session 支持的会话存储中检索和删除用户会话。
需要使用 Spring Session 的基于 Servlet 的 Web 应用程序。
shutdown 使应用程序正常关闭。默认禁用。
startup 显示由 ApplicationStartup 收集的启动步骤数据。
需要使用 SpringApplication 进行配置 BufferingApplicationStartup
threaddump 执行线程转储。
heapdump 返回 hprof 堆转储文件。
jolokia 通过 HTTP 暴露 JMX bean(需要引入 Jolokia,不适用于 WebFlux)。
需要引入依赖 jolokia-core
logfile 返回日志文件的内容(如果已设置 logging.file.name 或 logging.file.path 属性)。
支持使用 HTTPRange 标头来检索部分日志文件的内容。
prometheus 以 Prometheus 服务器可以抓取的格式公开指标。
需要依赖 micrometer-registry-prometheus

2.定制端点

● 健康监控:返回存活、死亡
● 指标监控:次数、率

(1)健康监控-HealthEndpoint

  • MyHahaComponent
  1. package com.atguigu.boot3.actuator.component;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. public class MyHahaComponent {
  5. public int check() {
  6. //业务代码判断这个组件是否为存活状态
  7. return 1;
  8. }
  9. }
  • MyHahaHealthIndicator
  1. package com.atguigu.boot3.actuator.health;
  2. import com.atguigu.boot3.actuator.component.MyHahaComponent;
  3. import jakarta.annotation.Resource;
  4. import org.springframework.boot.actuate.health.AbstractHealthIndicator;
  5. import org.springframework.boot.actuate.health.Health;
  6. import org.springframework.stereotype.Component;
  7. /**
  8. * 1. 通过实现 HealthIndicator 接口来定制组件的健康状态对象(Health) 返回
  9. * 2. 通过继承 AbstractHealthIndicator 实现 doHealthCheck 返回
  10. */
  11. @Component
  12. public class MyHahaHealthIndicator extends AbstractHealthIndicator {
  13. @Resource
  14. MyHahaComponent myHahaComponent;
  15. /**
  16. * 健康检查
  17. * @param builder
  18. * @throws Exception
  19. */
  20. @Override
  21. protected void doHealthCheck(Health.Builder builder) throws Exception {
  22. //自定义检查方法
  23. int check = myHahaComponent.check();
  24. if(check == 1) {
  25. //存活
  26. builder.up()
  27. .withDetail("code","1000")
  28. .withDetail("msg","活的很健康")
  29. .withDetail("data","我的名字是 Haha")
  30. .build();
  31. } else {
  32. //下线
  33. builder.down()
  34. .withDetail("code","1001")
  35. .withDetail("msg","死掉了")
  36. .withDetail("data","我的名字是 Haha")
  37. .build();
  38. }
  39. }
  40. }
  • 配置文件
  1. server.port= 9000
  2. #通过 web 方式暴露所有监控端点
  3. management.endpoints.web.exposure.include=*
  4. management.endpoint.health.enabled=true
  5. management.endpoint.health.show-details=always
  1. {
  2. "status":"UP",
  3. "components":{
  4. "diskSpace":{
  5. "status":"UP",
  6. "details":{
  7. "total":604120281088,
  8. "free":525610569728,
  9. "threshold":10485760,
  10. "path":"D:\\v_hwhao\\学习\\Code\\2023\\Java\\SpringBoot3-Study\\.",
  11. "exists":true
  12. }
  13. },
  14. "myHaha":{
  15. "status":"UP",
  16. "details":{
  17. "code":"1000",
  18. "msg":"活的很健康",
  19. "data":"我的名字是 Haha"
  20. }
  21. },
  22. "ping":{
  23. "status":"UP"
  24. }
  25. }
  26. }
  1. {
  2. "status":"DOWN",
  3. "components":{
  4. "diskSpace":{
  5. "status":"UP",
  6. "details":{
  7. "total":604120281088,
  8. "free":525610569728,
  9. "threshold":10485760,
  10. "path":"D:\\v_hwhao\\学习\\Code\\2023\\Java\\SpringBoot3-Study\\.",
  11. "exists":true
  12. }
  13. },
  14. "myHaha":{
  15. "status":"DOWN",
  16. "details":{
  17. "code":"1001",
  18. "msg":"死掉了",
  19. "data":"我的名字是 Haha"
  20. }
  21. },
  22. "ping":{
  23. "status":"UP"
  24. }
  25. }
  26. }

(2)指标监控-MetricsEndpoint

  • 修改 MyHahaComponent
  1. package com.atguigu.boot3.actuator.component;
  2. import io.micrometer.core.instrument.Counter;
  3. import io.micrometer.core.instrument.MeterRegistry;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class MyHahaComponent {
  7. /**
  8. * 计数器
  9. */
  10. Counter counter = null;
  11. /**
  12. * 有参构造函数
  13. * 注入 MeterRegistry,保存和统计所有指标
  14. * @param meterRegistry 指标统计参数
  15. */
  16. public MyHahaComponent(MeterRegistry meterRegistry) {
  17. //得到一个名为 myhaha.hello 的计数器
  18. counter = meterRegistry.counter("myhaha.hello");
  19. }
  20. public int check() {
  21. //业务代码判断这个组件是否为存活状态
  22. return 1;
  23. }
  24. public String hello() {
  25. //方法被调用,计数器 + 1
  26. counter.increment();
  27. return "hello";
  28. }
  29. }
  • 新建控制器- HelloController
  1. package com.atguigu.boot3.actuator.controller;
  2. import com.atguigu.boot3.actuator.component.MyHahaComponent;
  3. import jakarta.annotation.Resource;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class HelloController {
  8. @Resource
  9. MyHahaComponent myHahaComponent;
  10. @GetMapping("hello")
  11. public String hello() {
  12. //业务调用
  13. return myHahaComponent.hello();
  14. }
  15. }

监控案例落地

基于 Prometheus + Grafana

1.安装 Prometheus + Grafana

  1. #安装prometheus:时序数据库
  2. docker run -p 9090:9090 -d \
  3. -v pc:/etc/prometheus \
  4. prom/prometheus
  5. #安装grafana;默认账号密码 admin:admin
  6. docker run -d --name=grafana -p 3000:3000 grafana/grafana

2.导入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>io.micrometer</groupId>
  7. <artifactId>micrometer-registry-prometheus</artifactId>
  8. <version>1.10.6</version>
  9. </dependency>
  • 配置文件
  1. management:
  2. endpoints:
  3. web:
  4. exposure: #暴露所有监控的端点
  5. include: '*'

3.部署 Java 应用

  1. #安装上传工具
  2. yum install lrzsz
  3. #安装openjdk
  4. # 下载openjdk
  5. wget https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.tar.gz
  6. mkdir -p /opt/java
  7. tar -xzf jdk-17_linux-x64_bin.tar.gz -C /opt/java/
  8. sudo vi /etc/profile
  9. #加入以下内容
  10. export JAVA_HOME=/opt/java/jdk-17.0.7
  11. export PATH=$PATH:$JAVA_HOME/bin
  12. #环境变量生效
  13. source /etc/profile
  14. # 后台启动java应用
  15. nohup java -jar boot3-14-actuator-0.0.1-SNAPSHOT.jar > output.log 2>&1 &

确认可以访问到: http://8.130.32.70:9999/actuator/prometheus

4.配置 Prometheus 拉取数据

  1. ## 修改 prometheus.yml 配置文件
  2. scrape_configs:
  3. - job_name: 'spring-boot-actuator-exporter' #应用名称,可自定义
  4. metrics_path: '/actuator/prometheus' #指定抓取的路径
  5. static_configs:
  6. - targets: ['8.130.32.70:9999'] #Java 应用访问 IP + 端口
  7. labels:
  8. nodename: 'app-demo'

5.配置 Grafana 监控面板

● 添加数据源(Prometheus)
● 添加面板。可去 dashboard 市场找一个自己喜欢的面板,也可以自己开发面板; Dashboards | Grafana Labs