天天看點

springboot+Prometheus+grafana

作者:我是果東

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.class, args);
}
@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 gauge、jvm_gc_memory_promoted_bytes_total counter ,go_api_report_dial_request_count等

springboot+Prometheus+grafana

到此,Spring Boot 工程內建 Micrometer 就已經完成,接下裡就要與 Prometheus 進行內建了。

2.內建 Prometheus

  • 2.1安裝
```bash
docker pull prom/prometheus
```
```bash
mdkir /usr/local/prometheus
```
```bash
vi prometheus.yml           
# 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']
           
```bash
docker run -d --name prometheus -p 9090:9090 -v/usr/local/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
```           
springboot+Prometheus+grafana
  • 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 服務

springboot+Prometheus+grafana
springboot+Prometheus+grafana

3.使用 Grafana Dashboard 展示監控項

  • 3.1安裝grafana
```bash
docker pull grafana/grafana
```
```bash
docker run -d --name grafana -p 3000:3000 -v /usr/local/grafana:/var/lib/grafana grafana/grafana
```
           

預設使用者名/密碼 admin/admin

springboot+Prometheus+grafana
  • 3.2配置prometheus資料源
springboot+Prometheus+grafana
  • 3.3增加jvm面闆

模闆編号為4701

springboot+Prometheus+grafana
springboot+Prometheus+grafana
  • 3.4配置業務接口監控面闆
springboot+Prometheus+grafana