directory

  • Add dependencies
  • Installation and configuration of Prometheus
  • Grafana installation and configuration
  • 4. Customize monitoring indicators

Add dependencies

  • Maven pom.xml
<! -- Clause 1 must be added, Could not autowire. No beans of 'XXXX' type found --> <dependency> <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-core</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency>Copy the code
  • Gradle build.gradle
implementation 'org.springframework.boot:spring-boot-starter-actuator'
compile 'io.micrometer:micrometer-registry-prometheus'
compile 'io.micrometer:micrometer-core'

Copy the code
  • Open the Prometheus monitoring interfaceapplication.properties
server.port=8088
spring.application.name=springboot2-prometheus
management.endpoints.web.exposure.include=*
management.metrics.tags.application=${spring.application.name}

Copy the code

Visit http://localhost:8088/actuator/prometheus can run the program directly, can see the following content:

# HELP jvm_buffer_total_capacity_bytes An estimate of the total capacity of the buffers in this pool # TYPE Jvm_buffer_total_capacity_bytes the gauge jvm_buffer_total_capacity_bytes {id = "direct",} 90112.0 Jvm_buffer_total_capacity_bytes {id="mapped",} 0.0 # HELP tomcat_sessionS_expired_sessionS_total # TYPE Tomcat_sessions_expired_sessions_total Counter Tomcat_sessionS_expired_sessions_total 0.0 # HELP jvm_classes_unloaded_classes_total The total number of classes unloaded since the Java virtual machine has started Execution # TYPE jvm_classes_unloaded_classes_total counter jVM_classes_unloaded_classes_total 1.0 # HELP jvm_buffer_count_buffers An estimate of the number of buffers in the pool # TYPE jvm_buffer_count_buffers gauge Jvm_buffer_count_buffers {id="direct",} 11.0 jVM_buffer_count_buffers {id="mapped",} 0.0 # HELP system_cpu_usage The "Recent CPU usage" for the whole system # TYPE system_cpu_usage gauge system_cpu_usage 0.0939447637893599 # HELP jvm_gc_max_data_size_bytes Max size of old generation memory pool # TYPE jvm_gc_max_data_size_bytes gauge Jvm_gc_max_data_size_bytes 2.841116672E9 #Copy the code

Installation and configuration of Prometheus

Running Prometheus with Docker (initial test only)

docker run --name prometheus -d -p 9090:9090 prom/prometheus:latest

Copy the code

Write the configuration file 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). # 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: ['localhost:9090'] # demo job - job_name: 'springboot-actuator-prometheus-test' # job name metrics_path: '/actuator/ Prometheus' # scrape_interval: 5s # 'actuator' password: 'actuator' static_configs: - targets: [' docker. For. MAC. Localhost: 18080 '] # instance address, the default protocol is HTTP (here there is a problem, write directly localhost is access to the container address, instead of the host machine. To view the target service status, choose Status -> Targets on the upper part of the web pageCopy the code

Run the docker

docker run -d -p 9090:9090 -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus --config.file=/etc/prometheus/prometheus.yml

Copy the code

Visit http://localhost:9090 and you can see the following interface

  • Click on theInsert metric at cursor, you can select monitoring indicators; Click on theGraph, so that indicators can be displayed in the form of charts; Click on theExecuteButton, you can see the indicator chart

Grafana installation and configuration

1, start,

$ docker run -d --name=grafana -p 3000:3000 grafana/grafana 

Copy the code

2, login

Visit http://localhost:3000/login, the initial account/password: admin/admin

3. Configure the data source

  • Click the left gearConfigurationIn theAdd Data Source, you will see the following interface:

  • Here we select Prometheus as the data source, and here we configure the access address for Prometheus and clickSave & Test

4. Create a monitoring Dashboard

  • Click on the navigation bar+Button and click Dashboard to see something similar to the following

  • Click on the+ Add new panel

4. Customize monitoring indicators

1. Create Prometheus Monitor management class PrometheusCustomMonitor

import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.concurrent.atomic.AtomicInteger; @Component public class PrometheusCustomMonitor { private Counter requestErrorCount; private Counter orderCount; private DistributionSummary amountSum; private AtomicInteger failCaseNum; private final MeterRegistry registry; @Autowired public PrometheusCustomMonitor(MeterRegistry registry) { this.registry = registry; } @PostConstruct private void init() { requestErrorCount = registry.counter("requests_error_total", "status", "error"); orderCount = registry.counter("order_request_count", "order", "test-svc"); amountSum = registry.summary("order_amount_sum", "orderAmount", "test-svc"); failCaseNum = registry.gauge("fail_case_num", new AtomicInteger(0)); } public Counter getRequestErrorCount() { return requestErrorCount; } public Counter getOrderCount() { return orderCount; } public DistributionSummary getAmountSum() { return amountSum; } public AtomicInteger getFailCaseNum() { return failCaseNum; }}Copy the code

2. Add /order interface

When flag=”1″, throw exception, simulate the failure of order. Count order_request_count and order_amount_sum in the interface

import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.Random; @RestController public class TestController { @Resource private PrometheusCustomMonitor monitor; @RequestMapping("/order") public String order(@RequestParam(defaultValue = "0") String flag) throws Exception { // Monitor. GetOrderCount ().increment(); If ("1".equals(flag)) {throw new Exception(" error "); } Random random = new Random(); int amount = random.nextInt(100); Monitor.getamountsum ().record(amount); monitor.getFailCaseNum().set(amount); Return "order successfully, amount:" + amount; }}Copy the code

3. Added GlobalExceptionHandler GlobalExceptionHandler

Requests_error_total Indicates the number of failed orders

import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; @ControllerAdvice public class GlobalExceptionHandler { @Resource private PrometheusCustomMonitor monitor; @ResponseBody @ExceptionHandler(value = Exception.class) public String handle(Exception e) { monitor.getRequestErrorCount().increment(); return "error, message: " + e.getMessage(); }}Copy the code

4, test,

Start the project, visit http://localhost:8080/order and http://localhost:8080/order? Flag = 1 simulation order success and failure, and then we go to http://localhost:8080/actuator/prometheus, you can see our custom indicators has been exposed/Prometheus endpoint

# HELP requests_error_total # TYPE requests_error_total counter Requests_error_total {application = "springboot - physical - Prometheus - test", the status = "error",} # 41.0 HELP order_request_count_total # TYPE order_request_count_total counter Order_request_count_total {application = "springboot - physical - Prometheus - test", the order = "test - SVC",} # 94.0 HELP order_amount_sum # TYPE order_amount_sum summary Order_amount_sum_count {application = "springboot - physical - Prometheus - test", orderAmount = "test - SVC",} 53.0 Order_amount_sum_sum {application = "springboot - physical - Prometheus - test", orderAmount = "test - SVC",} 2701.0Copy the code

5. Monitor using Prometheus

Rerun the Docker

docker run -d -p 9090:9090 -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus --config.file=/etc/prometheus/prometheus.yml

Copy the code

You can view data changes after selecting indicators

6. Demonstrate using Grafana

Select a monitoring indicator on the Dashboard


References:

Metric types | Prometheus

IntelliJ IDEA creates the first Spring Boot project _Study Notes-CSDN blog

Monitor Java application performance with Prometheus integrated with Micrometer

Micrometer Application Monitoring

Spring Boot Microservice application integrates Prometheus + Grafana to monitor alarms

Monitoring the Java Spring Boot applications with Prometheus: Part 1 | by Arush Salil | Kubernauts “give up this tutorial?” The Client Java does not support SpringBoot 2.x and supports up to 1.5

Spring Boot Reference Guide (Endpoints) _ Wind continues to blow – SegmentFault think no