paulwong

          使用PROMETHEUS+GRAFANA監(jiān)控JAVA程序


          Grafana能夠提供自定義的圖形界面來展示監(jiān)控?cái)?shù)據(jù),但由于被監(jiān)控的應(yīng)用五花八門,標(biāo)準(zhǔn)不一,因此Prometheus開發(fā)了各種client,應(yīng)用程序只需引入該SDK,即可與Prometheus溝通,提供Prometheus格式的數(shù)據(jù),同時Grafana也開發(fā)了能識別Prometheus類型的數(shù)據(jù)源的插件,Grafana能夠展示Prometheus上的數(shù)據(jù)。

          非JAVA版本的應(yīng)用:

          <project xmlns="http://maven.apache.org/POM/4.0.0"
              xmlns:xsi
          ="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation
          ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
              <modelVersion>4.0.0</modelVersion>
              <groupId>com.paul</groupId>
              <artifactId>test-prometheus-java</artifactId>
              <version>0.0.1-SNAPSHOT</version>

              <properties>
                  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
                  <java.version>1.8</java.version>
                  <maven.compiler.source>${java.version}</maven.compiler.source>
                  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                  <maven.compiler.target>${java.version}</maven.compiler.target>
                  <micrometer.version>1.5.14</micrometer.version>
                  <prometheus.version>0.11.0</prometheus.version>
                  <start-class>com.paul.testprometheusjava.TestPrometheusJavaApplication</start-class>
              </properties>
              
              <dependencies>
              
                  <dependency>
                      <groupId>ch.qos.logback</groupId>
                      <artifactId>logback-classic</artifactId>
                      <version>1.2.3</version>
                  </dependency>
              
                  <dependency>
                      <groupId>org.apache.logging.log4j</groupId>
                      <artifactId>log4j-to-slf4j</artifactId>
                      <version>2.13.3</version>
                  </dependency>
              
                  <dependency>
                      <groupId>org.slf4j</groupId>
                      <artifactId>jul-to-slf4j</artifactId>
                      <version>1.7.30</version>
                  </dependency>
                  
                  <!-- https://mvnrepository.com/artifact/com.sun.net.httpserver/http -->
                  <!-- <dependency>
                      <groupId>com.sun.net.httpserver</groupId>
                      <artifactId>http</artifactId>
                      <version>20070405</version>
                  </dependency> 
          -->


                  <dependency>
                      <groupId>io.prometheus</groupId>
                      <artifactId>simpleclient_httpserver</artifactId>
                  </dependency>

                  <dependency>
                      <groupId>io.prometheus</groupId>
                      <artifactId>simpleclient_hotspot</artifactId>
                  </dependency>

                  <dependency>
                      <groupId>io.prometheus</groupId>
                      <artifactId>simpleclient_logback</artifactId>
                  </dependency>

                  <dependency>
                      <groupId>io.micrometer</groupId>
                      <artifactId>micrometer-registry-prometheus</artifactId>
                      <version>${micrometer.version}</version>
                  </dependency>
              
              </dependencies>
              
              <dependencyManagement>
                  <dependencies>
                      
                      <dependency>
                          <groupId>io.prometheus</groupId>
                          <artifactId>simpleclient_bom</artifactId>
                          <version>0.11.0</version>
                          <type>pom</type>
                          <scope>import</scope>
                      </dependency>
                      
                  </dependencies>
              </dependencyManagement>
              
              <build>
                  <plugins>

                      <plugin>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-maven-plugin</artifactId>
                          <version>2.3.11.RELEASE</version>
                          <executions>
                              <execution>
                                  <id>repackage</id>
                                  <goals>
                                      <goal>repackage</goal>
                                  </goals>
                                  <configuration>
                                      <mainClass>${start-class}</mainClass>
                                  </configuration>
                              </execution>
                          </executions>
                          <configuration>
                              <mainClass>${start-class}</mainClass>
                          </configuration>
                      </plugin>
                      
                  </plugins>
              </build>
              

          </project>

          PrometheusEndpoint
          package com.paul.testprometheusjava.web.endpoint;

          import java.io.IOException;
          import java.io.OutputStream;
          import java.net.InetSocketAddress;

          import com.sun.net.httpserver.HttpServer;

          import io.micrometer.prometheus.PrometheusConfig;
          import io.micrometer.prometheus.PrometheusMeterRegistry;
          import io.prometheus.client.exporter.HTTPServer;
          import io.prometheus.client.hotspot.DefaultExports;
          import io.prometheus.client.logback.InstrumentedAppender;

          public class PrometheusEndpoint {
              
              public void startOld() {
                  PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
                  try {
                      HttpServer server = HttpServer.create(new InetSocketAddress(8081), 0);
                      server.createContext("/prometheus", httpExchange -> {
                          String response = prometheusRegistry.scrape();
                          httpExchange.sendResponseHeaders(200, response.getBytes().length);
                          try (OutputStream os = httpExchange.getResponseBody()) {
                              os.write(response.getBytes());
                          }
                      });

                      new Thread(server::start).start();
                  } catch (IOException e) {
                      throw new RuntimeException(e);
                  }
              }
              
              public void start() throws IOException {
                  DefaultExports.initialize();
                  new InstrumentedAppender();
                  new HTTPServer(8081);
              }

          }

          SPRING版本的應(yīng)用:


          pom.xml
          <?xml version="1.0" encoding="UTF-8"?>
          <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation
          ="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
              <modelVersion>4.0.0</modelVersion>
              <parent>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-parent</artifactId>
                  <version>2.3.11.RELEASE</version>
                  <relativePath/> <!-- lookup parent from repository -->
              </parent>
              <groupId>com.paul</groupId>
              <artifactId>test-prometheus</artifactId>
              <version>0.0.1-SNAPSHOT</version>
              <name>test-prometheus</name>
              <description>Demo project for Spring Boot</description>
              <properties>
                  <java.version>1.8</java.version>
              </properties>
              <dependencies>
                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-starter-web</artifactId>
                  </dependency>
                  
                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-starter-actuator</artifactId>
                  </dependency>
                  
                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-starter-security</artifactId>
                  </dependency>

                  <!-- Micormeter core dependecy -->
                  
                  <!-- Micrometer Prometheus registry -->
                  <dependency>
                      <groupId>io.micrometer</groupId>
                      <artifactId>micrometer-registry-prometheus</artifactId>
                  </dependency>

                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-starter-test</artifactId>
                      <scope>test</scope>
                      <exclusions>
                          <exclusion>
                              <groupId>org.junit.vintage</groupId>
                              <artifactId>junit-vintage-engine</artifactId>
                          </exclusion>
                      </exclusions>
                  </dependency>
              </dependencies>

              <build>
                  <plugins>
                      <plugin>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-maven-plugin</artifactId>
                      </plugin>
                  </plugins>
              </build>

          </project>


          TestPrometheusApplication

          package com.paul.testprometheus;

          import org.springframework.boot.SpringApplication;
          import org.springframework.boot.autoconfigure.SpringBootApplication;

          @SpringBootApplication
          public class TestPrometheusApplication {

              public static void main(String[] args) {
                  SpringApplication.run(TestPrometheusApplication.class, args);
              }

          }


          HelloController

          package com.paul.testprometheus.web.controller;

          import org.springframework.web.bind.annotation.GetMapping;
          import org.springframework.web.bind.annotation.RequestMapping;
          import org.springframework.web.bind.annotation.RestController;

          @RestController
          @RequestMapping("/api")
          public class HelloController{
           
             @GetMapping("/hello")
             public String printHello() {
                return "Hello Spring MVC Framework!";
             }

          }


          application.yml

          ## prometheus監(jiān)控配置
          management:
            server:
              port: 18080 # 修改actuator的端口
            metrics:
              export:
                prometheus:
                  enabled: true
                  step: 1m
                  descriptions: true
              tags:
                application: ${spring.application.name} # 暴露的數(shù)據(jù)中添加application label
            web:
              server:
                auto-time-requests: true
            endpoints:
              prometheus:
                id: springmetrics
              web:
          #     base-path: /xueqiu # 修改actuator的路徑名
                exposure:
                  include: health,prometheus
                  exclude: info,env,metrics,httptrace,threaddump,heapdump
                  
          spring:
            application:
              name: test-prometheus
            security: 
              user: 
                name: admin
                password: admin


          Prometheus安裝

          dowonload:
          https://prometheus.io/download/
          https://github.com/prometheus/prometheus/releases/download/v2.27.1/prometheus-2.27.1.linux-amd64.tar.gz

          installation:
          tar xvfz prometheus-*.tar.gz
          cd prometheus-*
          vi prometheus.yml

          # Start Prometheus.
          # By default, Prometheus stores its database in ./data (flag --storage.tsdb.path).
          ./prometheus --config.file=prometheus.yml


          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: 'test-prometheus'

              # metrics_path defaults to '/metrics'
              # scheme defaults to 'http'.
              
              # 多久采集一次數(shù)據(jù)    
              scrape_interval: 15s    
              # 采集時的超時時間    
              scrape_timeout: 10s    
              # 采集的路徑是啥    
              metrics_path: '/actuator/prometheus'
              # 采集服務(wù)的地址,設(shè)置成上面Spring Boot應(yīng)用所在服務(wù)器的具體地址。    
              scheme: http
              basic_auth:
                username: admin
                password: admin
              static_configs:
              - targets: ['localhost:18080']


          startup-prometheus.sh
          #! /bin/bash

          BIN_PATH=$(cd `dirname $0`; pwd)
          cd ${BIN_PATH}
          ./prometheus --config.file=prometheus.yml &

          https://www.fosslinux.com/10398/how-to-install-and-configure-prometheus-on-centos-7.htm

          Grafana安裝

          yum localinstall /path/to/grafana-8.0.0-1.x86_64.rpm

          systemctl daemon-reload
          systemctl start grafana-server
          systemctl status grafana-server

          systemctl enable grafana-server

          login ui:
          http://ip:3000
          admin:admin

          Step 3: Create a dashboard
          To create your first dashboard:

          1.Click the + icon on the side menu.
          2.On the dashboard, click Add an empty panel.
          3.In the New dashboard/Edit panel view, go to the Query tab.
          4.Configure your query by selecting -- Grafana -- from the data source selector. This generates the Random Walk dashboard.
          5.Click the Save icon in the top right corner of your screen to save the dashboard.
          6.Add a descriptive name, and then click Save.

          Congratulations, you have created your first dashboard and it is displaying results.

          import JVM (Micrometer) Dashboard by json:
          https://grafana.com/grafana/dashboards/4701
          https://grafana.com/api/dashboards/4701/revisions/9/download

          prometheus:
          http://ip:9090/

          https://www.fosslinux.com/8328/how-to-install-and-configure-grafana-on-centos-7.htm

          DASHBOARD的安裝
          import JVM (Micrometer) Dashboard by json:
          https://grafana.com/grafana/dashboards/4701
          https://grafana.com/api/dashboards/4701/revisions/9/download

          Spring Boot 2.1 Statistics:
          https://grafana.com/grafana/dashboards/10280
          https://grafana.com/api/dashboards/10280/revisions/1/download

          https://grafana.com/grafana/dashboards/6756
          https://grafana.com/api/dashboards/6756/revisions/2/download

          LINUX DASHBOARD:
          https://grafana.com/grafana/dashboards/8919
          https://grafana.com/api/dashboards/8919/revisions/24/download


          Reference:
          https://www.163.com/dy/article/GBIN9JGS0511BM5R.html#
          https://github.com/prometheus/client_java
          https://blog.frognew.com/2018/01/using-prometheus-to-monitor-java-application.html
          https://blog.csdn.net/singgel/article/details/101120430
          https://blog.csdn.net/aixiaoyang168/article/details/100866159

          posted on 2021-06-16 09:53 paulwong 閱讀(1038) 評論(0)  編輯  收藏 所屬分類: APM


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 凤冈县| 平乐县| 庄浪县| 黄骅市| 巴青县| 景德镇市| 黄大仙区| 锦屏县| 台中县| 阳泉市| 綦江县| 尉犁县| 东乌| 津南区| 湘阴县| 海晏县| 阿瓦提县| 琼海市| 隆德县| 通河县| 虎林市| 始兴县| 阿瓦提县| 电白县| 绍兴市| 克什克腾旗| 武宁县| 伽师县| 临湘市| 牡丹江市| 西安市| 栾川县| 天津市| 金湖县| 鸡泽县| 山东省| 兴业县| 张家口市| 岱山县| 齐齐哈尔市| 广宁县|