laitimes

springboot+Prometheus+grafana

author:I'm Goto

1.Spring Boot projects integrate Micrometer

  • 1.1 Introducing dependencies
<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 Configuration
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           

Here management.endpoints.web.exposure.include=* is configured to enable the Actuator service, because Spring Boot Actuator automatically configures an HTTP service with the URL /actuator/Prometheus for Prometheus to fetch data, but the service is turned off by default, and this configuration will open all actuators Serve.

The management.metrics.tags.application configuration will add the project application name to the tag in the meter registry, so that Prometheus can distinguish different services according to the application name.

  • 1.3 Monitor JVM information

Then add beans in the main class of the project startup to monitor JVM performance metric information as follows:

@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 Create custom monitoring

Monitor the number of requests and response times

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 Add specific service code monitoring
//统计请求次数
prometheusCustomMonitor.getReportDialRequestCount().increment();
long startTime = System.currentTimeMillis();
String company = HttpUtils.post(companyUrl,"");
//统计响应时间
long endTime = System.currentTimeMillis();
prometheusCustomMonitor.getReportDialResponseTime().record(endTime-startTime, TimeUnit.MILLISECONDS);           

Accessing the http://127.0.0.1:9001/actuator/prometheus in a browser allows you to see a range of different types of metrics information for the service, such as jvm_memory_used_bytes gauge, jvm_gc_memory_promoted_bytes_total counter, go_api_report_dial_ request_count and so on

springboot+Prometheus+grafana

At this point, the Spring Boot project integration with Micrometer is complete, and the next step is to integrate with Prometheus.

2. Integrate Prometheus

  • 2.1 Installation
```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 Integration configuration
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"]           

Here localhost:9001 is the service address started locally above, which is the service address that Prometheus will monitor. At the same time, you can add some application-related tags to facilitate the later execution of PromSQL query statements. Finally, restart the Prometheus service

springboot+Prometheus+grafana
springboot+Prometheus+grafana

3. Use Grafana Dashboard to display items

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

Default username/password admin/admin

springboot+Prometheus+grafana
  • 3.2 Configure the Prometheus data source
springboot+Prometheus+grafana
  • 3.3 Add JVM panel

The template number is 4701

springboot+Prometheus+grafana
springboot+Prometheus+grafana
  • 3.4 Configure the service interface monitoring panel
springboot+Prometheus+grafana