Redian新闻
>
SpringBoot+Prometheus+Grafana 实现自定义监控

SpringBoot+Prometheus+Grafana 实现自定义监控

公众号新闻

点击上方“芋道源码”,选择“设为星标

管她前浪,还是后浪?

能浪的浪,才是好浪!

每天 10:33 更新文章,每天掉亿点点头发...

源码精品专栏

 
来源:blog.csdn.net/GZ946/
article/details/126619218

1.Spring Boot 工程集成 Micrometer

1.1引入依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

1.2配置

management.server.port=9003
management.endpoints.web.exposure.include=*
management.endpoint.metrics.enabled=true
management.endpoint.health.show-details=always
management.endpoint.health.probes.enabled=true
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true
management.metrics.tags.application=voice-qc-backend

这里 management.endpoints.web.exposure.include=* 配置为开启 Actuator 服务,因为Spring Boot Actuator 会自动配置一个 URL 为 /actuator/Prometheus 的 HTTP 服务来供 Prometheus 抓取数据,不过默认该服务是关闭的,该配置将打开所有的 Actuator 服务。

management.metrics.tags.application 配置会将该工程应用名称添加到计量器注册表的 tag 中去,方便后边 Prometheus 根据应用名称来区分不同的服务。

1.3监控jvm信息

然后在工程启动主类中添加 Bean 如下来监控 JVM 性能指标信息:

@SpringBootApplication
public class GatewayDatumApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayDatumApplication.classargs);
    }

    @Bean
    MeterRegistryCustomizer<MeterRegistry> configurer(
            @Value("${spring.application.name}")
 String applicationName) 
{
        return (registry) -> registry.config().commonTags("application", applicationName);
    }

}

1.4创建自定义监控

监控请求次数与响应时间

package com.lianxin.gobot.api.monitor;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Author: GZ
 * @CreateTime: 2022-08-30  10:50
 * @Description: 自定义监控服务
 * @Version: 1.0
 */

@Component
public class PrometheusCustomMonitor {
    /**
     * 上报拨打请求次数
     */

    @Getter
    private Counter reportDialRequestCount;
    /**
     * 上报拨打URL
     */

    @Value("${lx.call-result-report.url}")
    private String callReportUrl;

    /**
     * 上报拨打响应时间
     */

    @Getter
    private Timer reportDialResponseTime;
    @Getter
    private final MeterRegistry registry;


    @Autowired
    public PrometheusCustomMonitor(MeterRegistry registry) {
        this.registry = registry;
    }

    @PostConstruct
    private void init() {
        reportDialRequestCount = registry.counter("go_api_report_dial_request_count""url",callReportUrl);
        reportDialResponseTime=  registry.timer("go_api_report_dial_response_time""url",callReportUrl);
    }
}

1.5添加具体业务代码监控

//统计请求次数
prometheusCustomMonitor.getReportDialRequestCount().increment();
long startTime = System.currentTimeMillis();
String company = HttpUtils.post(companyUrl,"");
//统计响应时间
long endTime = System.currentTimeMillis();
prometheusCustomMonitor.getReportDialResponseTime().record(endTime-startTime, TimeUnit.MILLISECONDS);

在浏览器访问 http://127.0.0.1:9001/actuator/prometheus ,就可以看到服务的一系列不同类型 metrics 信息,例如jvm_memory_used_bytes gaugejvm_gc_memory_promoted_bytes_total countergo_api_report_dial_request_count

到此,Spring Boot 工程集成 Micrometer 就已经完成,接下里就要与 Prometheus 进行集成了。

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro
  • 视频教程:https://doc.iocoder.cn/video/

2.集成 Prometheus

2.1安装

docker pull prom/prometheus
mdkir /usr/local/prometheus
vi prometheus.yml

> 基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
>
> * 项目地址:<https://github.com/YunaiV/yudao-cloud>
> * 视频教程:<https://doc.iocoder.cn/video/>

# my global config
global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
    - targets: ['192.168.136.129:9090']
docker run -d --name prometheus -p 9090:9090 -v/usr/local/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

2.2集成配置

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
    - targets: ["localhost:9090"]
  - job_name: "metricsLocalTest"
    metrics_path: "/actuator/prometheus"
    static_configs:
    - targets: ["localhost:9003"]

这里 localhost:9001 就是上边本地启动的服务地址,也就是 Prometheus 要监控的服务地址。同时可以添加一些与应用相关的标签,方便后期执行 PromSQL 查询语句区分。最后重启 Prometheus 服务

3.使用 Grafana Dashboard 展示监控项

3.1安装grafana

 docker pull grafana/grafana
docker run -d --name grafana -p 3000:3000 -v /usr/local/grafana:/var/lib/grafana grafana/grafana

默认用户名/密码 admin/admin

3.2配置prometheus数据源

3.3增加jvm面板

模板编号为4701

3.4配置业务接口监控面板



欢迎加入我的知识星球,一起探讨架构,交流源码。加入方式,长按下方二维码噢

已在知识星球更新源码解析如下:

最近更新《芋道 SpringBoot 2.X 入门》系列,已经 101 余篇,覆盖了 MyBatis、Redis、MongoDB、ES、分库分表、读写分离、SpringMVC、Webflux、权限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能测试等等内容。

提供近 3W 行代码的 SpringBoot 示例,以及超 4W 行代码的电商微服务项目。

获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

文章有帮助的话,在看,转发吧。

谢谢支持哟 (*^__^*)

微信扫码关注该文公众号作者

戳这里提交新闻线索和高质量文章给我们。
相关阅读
用Prometheus监控K8s,从核心原理到告警实操都讲明白了 | 极客时间K8s + Prometheus = 监控神器Prometheus Metric 的实践总结,搞定监控需注意~SpringBoot + Flyway,自动化实现数据库版本控制Prometheus API 使用介绍SpringBoot + MDC 实现全链路调用日志跟踪SpringBoot 实现 Excel 导入导出,百万数据量,性能爆表!Lenovo Tab M8 HD 8" 2GB RAM & 32GB eMMC Tablet Iron GreySpring Boot+Netty+Websocket实现后台向前端推送信息如何解决Prometheus的存储容量问题?迷宫Far From Home: Meet the Migrants Returning to ShanghaiK8s + SpringBoot实现零宕机发布Prompt总结 | 从MLM预训任务到Prompt Learning原理解析与Zero-shot分类、NER简单实践SpringBoot超大文件上传,实现秒传SpringBoot 整合 Groovy 脚本,实现动态编程性能爆表:SpringBoot利用ThreadPoolTaskExecutor批量插入百万级数据实测!The Chinese Online Slang That Took Over the Internet in 2022如何快速构建Prometheus监控体系,架构、指标、数据、告警… | 极客时间主流监控系统 Prometheus 学习指南困恼诺奖作者埃尔诺一生的羞辱SpringBoot 应用的新命令行界面:JustSpringBoot+Flowable 快速实现工作流,so easy!Recommend somebody to do something是错误说法吗?糖是毒药吗?大脑为什么离不开葡萄糖?九大投行|Deutsche Bank 2023 China Graduate Programme 火热进行中![电脑] The Grand Beyond The Grand —— 华硕ROG HYPERION创世神 装机SHOW!SpringBoot+ElasticSearch 实现模糊查询,批量CRUD,排序,分页,高亮Go二次开发实战:K8s、Prometheus、Traefk的微服务网关Combo(i7-9700f/16gram 2666mhz/msi z390-a pro motherboard)prometheus和zabbix的对比你是TOFI吗Zabbix 和 Prometheus 到底怎么选?千万别用错了SpringBoot + Prometheus + Grafana 打造可视化监控一条龙!习家军的形成
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。