当前位置:   article > 正文

Springboot集成prometheus快速入门demo

Springboot集成prometheus快速入门demo

一、介绍

prometheus

Prometheus 是由前 Google 工程师从 2012 年开始在 Soundcloud 以开源软件的形式进行研发的系统监控和告警工具包,自此以后,许多公司和组织都采用了 Prometheus 作为监控告警工具。Prometheus 的开发者和用户社区非常活跃,它现在是一个独立的开源项目,可以独立于任何公司进行维护。为了证明这一点,Prometheus 于 2016 年 5 月加入 CNCF 基金会,成为继 Kubernetes 之后的第二个 CNCF 托管项目

grafana

Grafana 是一个监控仪表系统,它是由 Grafana Labs 公司开源的的一个系统监测工具,它可以大大帮助我们简化监控的复杂度,我们只需要提供需要监控的数据,它就可以帮助生成各种可视化仪表,同时它还有报警功能,可以在系统出现问题时发出通知。

二、环境搭建

这里采用docker-compose搭建测试环境,具体配置如下

docker-compose-prometheus.yml

 
 
  1. # 镜像版本请自行选择 https://hub.docker.com/search?q=&type=image
  2. version: "3"
  3. # 网桥 -> 方便相互通讯
  4. networks:
  5. prometheus:
  6. ipam:
  7. driver: default
  8. config:
  9. - subnet: "172.22.0.0/24"
  10. services:
  11. # 开源的系统监控和报警系统
  12. prometheus:
  13. image: registry.cn-hangzhou.aliyuncs.com/zhengqing/prometheus:v2.34.0 # 原镜像`prom/prometheus:v2.34.0`
  14. container_name: prometheus
  15. restart: unless-stopped
  16. volumes:
  17. - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
  18. command: "--config.file=/etc/prometheus/prometheus.yml --storage.tsdb.path=/prometheus"
  19. ports:
  20. - "9090:9090"
  21. depends_on:
  22. - node-exporter
  23. networks:
  24. prometheus:
  25. ipv4_address: 172.22.0.11
  26. # 采集服务器层面的运行指标
  27. node-exporter:
  28. image: registry.cn-hangzhou.aliyuncs.com/zhengqing/node-exporter:v1.3.1 # 原镜像`prom/node-exporter:v1.3.1`
  29. container_name: prometheus-node-exporter
  30. restart: unless-stopped
  31. ports:
  32. - "9100:9100"
  33. networks:
  34. prometheus:
  35. ipv4_address: 172.22.0.22
  36. # 用于UI展示
  37. # https://grafana.com/docs/grafana/latest/installation/docker
  38. grafana:
  39. image: registry.cn-hangzhou.aliyuncs.com/zhengqing/grafana:8.0.0 # 原镜像`grafana/grafana:8.0.0`
  40. container_name: prometheus-grafana
  41. restart: unless-stopped
  42. ports:
  43. - "3000:3000"
  44. volumes:
  45. - "./prometheus/grafana/grafana.ini:/etc/grafana/grafana.ini" # 邮箱配置
  46. # - "./prometheus/grafana/grafana-storage:/var/lib/grafana"
  47. # - "./prometheus/grafana/public:/usr/share/grafana/public" # 这里面可处理汉化包 可参考 https://github.com/WangHL0927/grafana-chinese
  48. # - "./prometheus/grafana/conf:/usr/share/grafana/conf"
  49. # - "./prometheus/grafana/log:/var/log/grafana"
  50. # - "/etc/localtime:/etc/localtime"
  51. environment:
  52. GF_EXPLORE_ENABLED: "true"
  53. GF_SECURITY_ADMIN_PASSWORD: "admin"
  54. GF_INSTALL_PLUGINS: "grafana-clock-panel,grafana-simple-json-datasource,alexanderzobnin-zabbix-app"
  55. # 持久化到mysql数据库
  56. GF_DATABASE_URL: "mysql://root:root@172.22.0.34:3306/grafana" # TODO 修改
  57. depends_on:
  58. - prometheus
  59. - mysql
  60. networks:
  61. prometheus:
  62. ipv4_address: 172.22.0.33
  63. # mysql数据库 => 用于grafana持久化数据
  64. mysql:
  65. image: registry.cn-hangzhou.aliyuncs.com/zhengqing/mysql:5.7
  66. container_name: prometheus-mysql
  67. restart: unless-stopped
  68. volumes:
  69. - "./prometheus/mysql5.7/my.cnf:/etc/mysql/my.cnf"
  70. - "./prometheus/mysql5.7/data:/var/lib/mysql"
  71. - "./prometheus/mysql5.7/log/mysql/error.log:/var/log/mysql/error.log"
  72. environment:
  73. TZ: Asia/Shanghai
  74. LANG: en_US.UTF-8
  75. MYSQL_ROOT_PASSWORD: root # 设置root用户密码
  76. MYSQL_DATABASE: grafana # 初始化数据库grafana
  77. ports:
  78. - "3306:3306"
  79. networks:
  80. prometheus:
  81. ipv4_address: 172.22.0.34

启动测试环境

docker-compose-prometheus.yml 需修改grafana中配置的mysql连接信息 prometheus.yml 自行配置

 
 
  1. # 运行
  2. docker-compose -f docker-compose-prometheus.yml -p prometheus up -d
  3. # 查看grafana日志
  4. docker logs -fn10 prometheus-grafana
  1. grafana访问地址:http://ip地址:3000 默认登录账号密码:admin/admin

  2. prometheus访问地址: http://ip地址:9090

  3. exporter访问地址: http://ip地址:9100/metrics

5a8a4b0eea1e7156e3ede862d41bb68a.png

三、代码工程

下面老做一个小实验,实现自定义监控指标

pom.xml

 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>springboot-demo</artifactId>
  7. <groupId>com.et</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>prometheus</artifactId>
  12. <properties>
  13. <maven.compiler.source>8</maven.compiler.source>
  14. <maven.compiler.target>8</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-web</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-autoconfigure</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-actuator</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>io.micrometer</groupId>
  31. <artifactId>micrometer-core</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>io.micrometer</groupId>
  35. <artifactId>micrometer-registry-prometheus</artifactId>
  36. </dependency>
  37. </dependencies>
  38. </project>

application.properties

 
 
  1. server.port=8088
  2. spring.application.name=springboot2-prometheus
  3. management.endpoints.web.exposure.include=*
  4. management.metrics.tags.application=${spring.application.name}

PrometheusCustomMonitor.java

 
 
  1. package com.et.prometheus.monitor;
  2. import io.micrometer.core.instrument.Counter;
  3. import io.micrometer.core.instrument.DistributionSummary;
  4. import io.micrometer.core.instrument.MeterRegistry;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Component;
  7. import javax.annotation.PostConstruct;
  8. import java.util.concurrent.atomic.AtomicInteger;
  9. @Component
  10. public class PrometheusCustomMonitor {
  11. private Counter requestErrorCount;
  12. private Counter orderCount;
  13. private DistributionSummary amountSum;
  14. private AtomicInteger failCaseNum;
  15. private final MeterRegistry registry;
  16. @Autowired
  17. public PrometheusCustomMonitor(MeterRegistry registry) {
  18. this.registry = registry;
  19. }
  20. @PostConstruct
  21. private void init() {
  22. requestErrorCount = registry.counter("requests_error_total", "status", "error");
  23. orderCount = registry.counter("order_request_count", "order", "test-svc");
  24. amountSum = registry.summary("order_amount_sum", "orderAmount", "test-svc");
  25. failCaseNum = registry.gauge("fail_case_num", new AtomicInteger(0));
  26. }
  27. public Counter getRequestErrorCount() {
  28. return requestErrorCount;
  29. }
  30. public Counter getOrderCount() {
  31. return orderCount;
  32. }
  33. public DistributionSummary getAmountSum() {
  34. return amountSum;
  35. }
  36. public AtomicInteger getFailCaseNum() {
  37. return failCaseNum;
  38. }
  39. }

GlobalExceptionHandler.java

 
 
  1. package com.et.prometheus.exception;
  2. import com.et.prometheus.monitor.PrometheusCustomMonitor;
  3. import org.springframework.web.bind.annotation.ControllerAdvice;
  4. import org.springframework.web.bind.annotation.ExceptionHandler;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. import javax.annotation.Resource;
  7. @ControllerAdvice
  8. public class GlobalExceptionHandler {
  9. @Resource
  10. private PrometheusCustomMonitor monitor;
  11. @ResponseBody
  12. @ExceptionHandler(value = Exception.class)
  13. public String handle(Exception e) {
  14. monitor.getRequestErrorCount().increment();
  15. return "error, message: " + e.getMessage();
  16. }
  17. }

TestController.java

 
 
  1. package com.et.prometheus.controller;
  2. import com.et.prometheus.monitor.PrometheusCustomMonitor;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import javax.annotation.Resource;
  7. import java.util.Random;
  8. @RestController
  9. public class TestController {
  10. @Resource
  11. private PrometheusCustomMonitor monitor;
  12. @RequestMapping("/order")
  13. public String order(@RequestParam(defaultValue = "0") String flag) throws Exception {
  14. // 统计下单次数
  15. monitor.getOrderCount().increment();
  16. if ("1".equals(flag)) {
  17. throw new Exception("出错啦");
  18. }
  19. Random random = new Random();
  20. int amount = random.nextInt(100);
  21. // 统计金额
  22. monitor.getAmountSum().record(amount);
  23. monitor.getFailCaseNum().set(amount);
  24. return "下单成功, 金额: " + amount;
  25. }
  26. }

启动类:

 
 
  1. package com.et.prometheus;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class DemoApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(DemoApplication.class, args);
  8. }
  9. }

code repository

  • https://github.com/Harries/springboot-demo

四、测试

启动springboot服务,,访问http://localhost:8089/orderhttp://localhost:8089/order?flag=1模拟下单成功和失败的情况,然后我们访问http://localhost:8088/actuator/prometheus,可以看到我们自定义指标已经被 /prometheus 端点暴露出来

 
 
  1. # TYPE order_request_count_total counter
  2. order_request_count_total{application="springboot2-prometheus",order="test-svc",} 34.0
  3. # HELP jvm_threads_daemon_threads The current number of live daemon threads
  4. # TYPE jvm_threads_daemon_threads gauge
  5. jvm_threads_daemon_threads{application="springboot2-prometheus",} 18.0
  6. # HELP jvm_classes_loaded_classes The number of classes that are currently loaded in the Java virtual machine
  7. # TYPE jvm_classes_loaded_classes gauge
  8. jvm_classes_loaded_classes{application="springboot2-prometheus",} 7250.0
  9. # HELP order_amount_sum_max
  10. # TYPE order_amount_sum_max gauge
  11. order_amount_sum_max{application="springboot2-prometheus",orderAmount="test-svc",} 97.0
  12. # HELP order_amount_sum
  13. # TYPE order_amount_sum summary
  14. order_amount_sum_count{application="springboot2-prometheus",orderAmount="test-svc",} 34.0
  15. order_amount_sum_sum{application="springboot2-prometheus",orderAmount="test-svc",} 1482.0

在grafana上配置自定义的监控参数

访问 http://localhost:3000/login ,初始账号/密码为:admin/admin

1、配置数据源

点击左侧齿轮ConfigurationAdd Data Source,会看到如下界面:57402f241302a257e656fa06236f9430.png这里我们选择Prometheus 当做数据源,这里我们就配置一下Prometheus 的访问地址,点击 Save & Test711163eeca6583fc89a1ee03e05dc519.png

2、创建监控 Dashboard

点击导航栏上的 + 按钮,并点击Dashboard,将会看到类似如下的界面7139dbda6ef4eab2903ee981d4a587e9.png点击+ Add new panel9b038898728d18f2cd357e0b7869c749.png

最终效果如下

a10a75f62a6f2ba2dc349a4f71603e27.png

五、引用

  • https://segmentfault.com/a/1190000040239129

  • http://www.liuhaihua.cn/archives/710215.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/146729?site
推荐阅读
相关标签
  

闽ICP备14008679号