基于Prometheus搭建SpringCloud全方位立體監(jiān)控體系

前提

最近公司在聯(lián)合運(yùn)維做一套全方位監(jiān)控的系統(tǒng),應(yīng)用集群的技術(shù)棧是SpringCloud體系。雖然本人沒(méi)有參與具體基礎(chǔ)架構(gòu)的研發(fā),但是從應(yīng)用引入的包和一些資料的查閱大致推算出具體的實(shí)現(xiàn)方案,這里做一次推演,詳細(xì)記錄一下整個(gè)搭建過(guò)程。

Prometheus是什么

Prometheus(普羅米修斯,官網(wǎng)是https://prometheus.io/),是一個(gè)開(kāi)源的系統(tǒng)監(jiān)控和告警的工具包,其采用Pull方式采集時(shí)間序列的度量數(shù)據(jù),通過(guò)Http協(xié)議傳輸。它的工作方式是被監(jiān)控的服務(wù)需要公開(kāi)一個(gè)Prometheus端點(diǎn),這端點(diǎn)是一個(gè)HTTP接口,該接口公開(kāi)了度量的列表和當(dāng)前的值,然后Prometheus應(yīng)用從此接口定時(shí)拉取數(shù)據(jù),一般可以存放在時(shí)序數(shù)據(jù)庫(kù)中,然后通過(guò)可視化的Dashboard(例如Promdash或者Grafana)進(jìn)行數(shù)據(jù)展示。當(dāng)然,此文章不打算深入研究這個(gè)工具,只做應(yīng)用層面的展示。這篇文章將會(huì)用到下面幾個(gè)技術(shù)棧:

  • SpringCloud體系,主要是注冊(cè)中心和注冊(cè)客戶端。
  • spring-boot-starter-actuator,主要是提供了Prometheus端點(diǎn),不用重復(fù)造輪子。
  • Prometheus的Java客戶端。
  • Prometheus應(yīng)用。
  • io.micrometer,SpringBoot標(biāo)準(zhǔn)下使用的度量工具包。
  • Grafana,可視化的Dashboard。

這里所有的軟件或者依賴全部使用當(dāng)前的最新版本,如果有坑踩了再填。其實(shí),Prometheus本身也開(kāi)發(fā)了一套Counter、Gauge、Timer等相關(guān)接口,不過(guò)SpringBoot中使用了io.micrometer中的套件,所以本文不深入分析Prometheus的Java客戶端。

io.micrometer的使用

在SpringBoot2.X中,spring-boot-starter-actuator引入了io.micrometer,對(duì)1.X中的metrics進(jìn)行了重構(gòu),主要特點(diǎn)是支持tag/label,配合支持tag/label的監(jiān)控系統(tǒng),使得我們可以更加方便地對(duì)metrics進(jìn)行多維度的統(tǒng)計(jì)查詢及監(jiān)控。io.micrometer目前支持Counter、Gauge、Timer、Summary等多種不同類(lèi)型的度量方式(不知道有沒(méi)有遺漏),下面逐個(gè)簡(jiǎn)單分析一下它們的作用和使用方式。 需要在SpringBoot項(xiàng)目下引入下面的依賴:

<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-core</artifactId>
  <version>${micrometer.version}</version>
</dependency>

目前最新的micrometer.version為1.0.5。注意一點(diǎn)的是:io.micrometer支持Tag(標(biāo)簽)的概念,Tag是其metrics是否能夠有多維度的支持的基礎(chǔ),Tag必須成對(duì)出現(xiàn),也就是必須配置也就是偶數(shù)個(gè)Tag,有點(diǎn)類(lèi)似于K-V的關(guān)系。

Counter

Counter(計(jì)數(shù)器)簡(jiǎn)單理解就是一種只增不減的計(jì)數(shù)器。它通常用于記錄服務(wù)的請(qǐng)求數(shù)量、完成的任務(wù)數(shù)量、錯(cuò)誤的發(fā)生數(shù)量等等。舉個(gè)例子:

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

/**
 * @author throwable
 * @version v1.0
 * @description
 * @since 2018/7/19 23:10
 */
public class CounterSample {

    public static void main(String[] args) throws Exception {
        //tag必須成對(duì)出現(xiàn),也就是偶數(shù)個(gè)
        Counter counter = Counter.builder("counter")
                .tag("counter", "counter")
                .description("counter")
                .register(new SimpleMeterRegistry());
        counter.increment();
        counter.increment(2D);
        System.out.println(counter.count());
        System.out.println(counter.measure());
        //全局靜態(tài)方法
        Metrics.addRegistry(new SimpleMeterRegistry());
        counter = Metrics.counter("counter", "counter", "counter");
        counter.increment(10086D);
        counter.increment(10087D);
        System.out.println(counter.count());
        System.out.println(counter.measure());
    }
}

輸出:

3.0
[Measurement{statistic='COUNT', value=3.0}]
20173.0
[Measurement{statistic='COUNT', value=20173.0}]

Counter的Measurement的statistic(可以理解為度量的統(tǒng)計(jì)角度)只有COUNT,也就是它只具備計(jì)數(shù)(它只有增量的方法,因此只增不減),這一點(diǎn)從它的接口定義可知:

public interface Counter extends Meter {

  default void increment() {
        increment(1.0);
  }

  void increment(double amount);

  double count();

  //忽略其他方法或者成員
}

Counter還有一個(gè)衍生類(lèi)型FunctionCounter,它是基于函數(shù)式接口ToDoubleFunction進(jìn)行計(jì)數(shù)統(tǒng)計(jì)的,用法差不多。

Gauge

Gauge(儀表)是一個(gè)表示單個(gè)數(shù)值的度量,它可以表示任意地上下移動(dòng)的數(shù)值測(cè)量。Gauge通常用于變動(dòng)的測(cè)量值,如當(dāng)前的內(nèi)存使用情況,同時(shí)也可以測(cè)量上下移動(dòng)的"計(jì)數(shù)",比如隊(duì)列中的消息數(shù)量。舉個(gè)例子:

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author throwable
 * @version v1.0
 * @description
 * @since 2018/7/19 23:30
 */
public class GaugeSample {

    public static void main(String[] args) throws Exception {
        AtomicInteger atomicInteger = new AtomicInteger();
        Gauge gauge = Gauge.builder("gauge", atomicInteger, AtomicInteger::get)
                .tag("gauge", "gauge")
                .description("gauge")
                .register(new SimpleMeterRegistry());
        atomicInteger.addAndGet(5);
        System.out.println(gauge.value());
        System.out.println(gauge.measure());
        atomicInteger.decrementAndGet();
        System.out.println(gauge.value());
        System.out.println(gauge.measure());
        //全局靜態(tài)方法,返回值竟然是依賴值,有點(diǎn)奇怪,暫時(shí)不選用
        Metrics.addRegistry(new SimpleMeterRegistry());
        AtomicInteger other = Metrics.gauge("gauge", atomicInteger, AtomicInteger::get);
    }
}

輸出結(jié)果:

5.0
[Measurement{statistic='VALUE', value=5.0}]
4.0
[Measurement{statistic='VALUE', value=4.0}]

Gauge關(guān)注的度量統(tǒng)計(jì)角度是VALUE(值),它的構(gòu)建方法中依賴于函數(shù)式接口ToDoubleFunction的實(shí)例(如例子中的實(shí)例方法引用AtomicInteger::get)和一個(gè)依賴于ToDoubleFunction改變自身值的實(shí)例(如例子中的AtomicInteger實(shí)例),它的接口方法如下:

public interface Gauge extends Meter {

  double value();

  //忽略其他方法或者成員
}

Timer

Timer(計(jì)時(shí)器)同時(shí)測(cè)量一個(gè)特定的代碼邏輯塊的調(diào)用(執(zhí)行)速度和它的時(shí)間分布。簡(jiǎn)單來(lái)說(shuō),就是在調(diào)用結(jié)束的時(shí)間點(diǎn)記錄整個(gè)調(diào)用塊執(zhí)行的總時(shí)間,適用于測(cè)量短時(shí)間執(zhí)行的事件的耗時(shí)分布,例如消息隊(duì)列消息的消費(fèi)速率。舉個(gè)例子:

import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

import java.util.concurrent.TimeUnit;

/**
 * @author throwable
 * @version v1.0
 * @description
 * @since 2018/7/19 23:44
 */
public class TimerSample {

    public static void main(String[] args) throws Exception{
        Timer timer = Timer.builder("timer")
                .tag("timer","timer")
                .description("timer")
                .register(new SimpleMeterRegistry());
        timer.record(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            }catch (InterruptedException e){
                //ignore
            }
        });
        System.out.println(timer.count());
        System.out.println(timer.measure());
        System.out.println(timer.totalTime(TimeUnit.SECONDS));
        System.out.println(timer.mean(TimeUnit.SECONDS));
        System.out.println(timer.max(TimeUnit.SECONDS));
    }
}

輸出結(jié)果:

1
[Measurement{statistic='COUNT', value=1.0}, Measurement{statistic='TOTAL_TIME', value=2.000603975}, Measurement{statistic='MAX', value=2.000603975}]
2.000603975
2.000603975
2.000603975

Timer的度量統(tǒng)計(jì)角度主要包括記錄執(zhí)行的最大時(shí)間、總時(shí)間、平均時(shí)間、執(zhí)行完成的總?cè)蝿?wù)數(shù),它提供多種的統(tǒng)計(jì)方法變體:

public interface Timer extends Meter, HistogramSupport {

  void record(long amount, TimeUnit unit);

  default void record(Duration duration) {
      record(duration.toNanos(), TimeUnit.NANOSECONDS);
  }

  <T> T record(Supplier<T> f);
    
  <T> T recordCallable(Callable<T> f) throws Exception;

  void record(Runnable f);

  default Runnable wrap(Runnable f) {
      return () -> record(f);
  }

  default <T> Callable<T> wrap(Callable<T> f) {
    return () -> recordCallable(f);
  }

  //忽略其他方法或者成員
}

這些record或者包裝方法可以根據(jù)需要選擇合適的使用,另外,一些度量屬性(如下限和上限)或者單位可以自行配置,具體屬性的相關(guān)內(nèi)容可以查看DistributionStatisticConfig類(lèi),這里不詳細(xì)展開(kāi)。

另外,Timer有一個(gè)衍生類(lèi)LongTaskTimer,主要是用來(lái)記錄正在執(zhí)行但是尚未完成的任務(wù)數(shù),用法差不多。

Summary

Summary(摘要)用于跟蹤事件的分布。它類(lèi)似于一個(gè)計(jì)時(shí)器,但更一般的情況是,它的大小并不一定是一段時(shí)間的測(cè)量值。在micrometer中,對(duì)應(yīng)的類(lèi)是DistributionSummary,它的用法有點(diǎn)像Timer,但是記錄的值是需要直接指定,而不是通過(guò)測(cè)量一個(gè)任務(wù)的執(zhí)行時(shí)間。舉個(gè)例子:


import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

/**
 * @author throwable
 * @version v1.0
 * @description
 * @since 2018/7/19 23:55
 */
public class SummarySample {

    public static void main(String[] args) throws Exception {
        DistributionSummary summary = DistributionSummary.builder("summary")
                .tag("summary", "summary")
                .description("summary")
                .register(new SimpleMeterRegistry());
        summary.record(2D);
        summary.record(3D);
        summary.record(4D);
        System.out.println(summary.measure());
        System.out.println(summary.count());
        System.out.println(summary.max());
        System.out.println(summary.mean());
        System.out.println(summary.totalAmount());
    }
}

輸出結(jié)果:

[Measurement{statistic='COUNT', value=3.0}, Measurement{statistic='TOTAL', value=9.0}, Measurement{statistic='MAX', value=4.0}]
3
4.0
3.0
9.0

Summary的度量統(tǒng)計(jì)角度主要包括記錄過(guò)的數(shù)據(jù)中的最大值、總數(shù)值、平均值和總次數(shù)。另外,一些度量屬性(如下限和上限)或者單位可以自行配置,具體屬性的相關(guān)內(nèi)容可以查看DistributionStatisticConfig類(lèi),這里不詳細(xì)展開(kāi)。

小結(jié)

一般情況下,上面的Counter、Gauge、Timer、DistributionSummary例子可以滿足日常開(kāi)發(fā)需要,但是有些高級(jí)的特性這里沒(méi)有展開(kāi),具體可以參考micrometer-spring-legacy這個(gè)依賴包,畢竟源碼是老師,源碼不會(huì)騙人。

spring-boot-starter-actuator的使用

spring-boot-starter-actuator在2.X版本中不僅升級(jí)了metrics為io.micrometer,很多配置方式也和1.X完全不同,鑒于前段時(shí)間沒(méi)有維護(hù)SpringBoot技術(shù)棧的項(xiàng)目,現(xiàn)在重新看了下官網(wǎng)復(fù)習(xí)一下。引入依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>${springboot.version}</version>
</dependency>

目前最新的springboot.version為2.0.3.RELEASE。在spring-boot-starter-actuator中,最大的變化就是配置的變化,原來(lái)在1.X版本是通過(guò)management.security.enabled控制是否可以忽略權(quán)限訪問(wèn)所有的監(jiān)控端點(diǎn),在2.X版本中,必須顯式配置不需要權(quán)限驗(yàn)證對(duì)外開(kāi)放的端點(diǎn):

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
management.endpoints.jmx.exposure.include=
management.endpoints.jmx.exposure.include=*

例如上面的配置,訪問(wèn)非/env和非/beans的端點(diǎn),可以不受權(quán)限控制,也就是所有人都可以訪問(wèn)非/env和非/beans的端點(diǎn)。例如,如果我只想暴露/health端點(diǎn),只需配置:

management.endpoints.web.exposure.include=health

這一點(diǎn)需要特別注意,其他使用和1.X差不多。還有一點(diǎn)是,2.X中所有監(jiān)控端點(diǎn)的訪問(wèn)url的默認(rèn)路徑前綴為:http://{host}/{port}/actuator/,也就是想訪問(wèn)health端點(diǎn)就要訪問(wèn)http://{host}/{port}/actuator/health,當(dāng)然也可以修改/actuator這個(gè)路徑前綴。其他細(xì)節(jié)區(qū)別沒(méi)有深入研究,可以參考文檔。

搭建SpringCloud應(yīng)用

接著先搭建一個(gè)SpringCloud應(yīng)用群,主要包括注冊(cè)中心(registry-center)和一個(gè)簡(jiǎn)單的服務(wù)節(jié)點(diǎn)(cloud-prometheus-sample),其中注冊(cè)中心只引入eureka-server的依賴,而服務(wù)節(jié)點(diǎn)用于對(duì)接Prometheus,引入eureka-client、spring-boot-starter-actuator、prometheus等依賴。

registry-center

registry-center是一個(gè)單純的服務(wù)注冊(cè)中心,只需要引入eureka-server的依賴,添加一個(gè)啟動(dòng)類(lèi)即可,添加的依賴如下:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

添加一個(gè)啟動(dòng)類(lèi):

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * @author throwable
 * @version v1.0
 * @description
 * @since 2018/7/21 9:06
 */
@SpringBootApplication
@EnableEurekaServer
public class RegistryCenterApplication {

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

配置文件application.yaml如下:

server:
  port: 9091
spring:
  application:
    name: registry-center
eureka:
  instance:
    hostname: localhost
  client:
    enabled: true
    register-with-eureka: false
    fetch-registry: false
    service-url:
         defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

就是這么簡(jiǎn)單,啟動(dòng)入口類(lèi)即可,啟動(dòng)的端口為9091。

cloud-prometheus-sample

cloud-prometheus-sample主要作為eureka-client,接入spring-boot-starter-actuator和prometheus依賴,引入依賴如下:

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

這里引入的是micrometer-registry-prometheus而不是micrometer-spring-legacy是因?yàn)?code>micrometer-spring-legacy是spring-integration(spring系統(tǒng)集成)的依賴,這里沒(méi)有用到,但是里面很多實(shí)現(xiàn)可以參考。micrometer-registry-prometheus提供了基于actuator的端點(diǎn),路徑是../prometheus。啟動(dòng)類(lèi)如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * @author throwable
 * @version v1.0
 * @description
 * @since 2018/7/21 9:13
 */
@SpringBootApplication
@EnableEurekaClient
public class SampleApplication {

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

配置文件application.yaml如下:

server:
  port: 9092
spring:
  application:
    name: cloud-prometheus-sample
eureka:
  instance:
    hostname: localhost
  client:
    service-url: http://localhost:9091/eureka/

啟動(dòng)端口為9092,eureka的服務(wù)注冊(cè)地址為:http://localhost:9091/eureka/,也就是registry-center中指定的默認(rèn)數(shù)據(jù)區(qū)(defaultZone)的注冊(cè)地址,先啟動(dòng)registry-center,再啟動(dòng)cloud-prometheus-sample,然后訪問(wèn)http://localhost:9091/

sp-p-1

訪問(wèn)http://localhost:9092/actuator/prometheus

sp-p-2

這些數(shù)據(jù)就是實(shí)時(shí)的度量數(shù)據(jù),Prometheus(軟件)配置好任務(wù)并且啟動(dòng)執(zhí)行后,就是通過(guò)定時(shí)拉取/prometheus這個(gè)端點(diǎn)返回的數(shù)據(jù)進(jìn)行數(shù)據(jù)聚合和展示的。

接著,我們先定制一個(gè)功能,統(tǒng)計(jì)cloud-prometheus-sample所有入站的Http請(qǐng)求數(shù)量(包括成功、失敗和非法的),添加如下代碼:

//請(qǐng)求攔截器
@Component
public class SampleMvcInterceptor extends HandlerInterceptorAdapter {

    private static final Counter COUNTER = Counter.builder("Http請(qǐng)求統(tǒng)計(jì)")
            .tag("HttpCount", "HttpCount")
            .description("Http請(qǐng)求統(tǒng)計(jì)")
            .register(Metrics.globalRegistry);

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        COUNTER.increment();
    }
}
//自定義Mvc配置
@Component
public class SampleWebMvcConfigurer implements WebMvcConfigurer {

    @Autowired
    private SampleMvcInterceptor sampleMvcInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sampleMvcInterceptor);
    }
}

重啟cloud-prometheus-sample,直接訪問(wèn)幾次不存在的根節(jié)點(diǎn)路徑http://localhost:9092/,再查看端點(diǎn)統(tǒng)計(jì)數(shù)據(jù):

sp-p-3

安裝和使用Prometheus

先從Prometheus官方下載地址下載軟件,這里用Windows10平臺(tái)演示,直接下載prometheus-2.3.2.windows-amd64.tar.gz,個(gè)人有軟件潔癖,用軟件或者依賴喜歡最高版本,出現(xiàn)坑了自己填。解壓后目錄如下:

sp-p-4

啟動(dòng)的話,直接運(yùn)行prometheus.exe即可,這里先配置一下prometheus.yml:

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.
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093
scrape_configs:
  - job_name: 'prometheus'
    metrics_path: /actuator/prometheus
    static_configs:
    - targets: ['localhost:9092']

我們主要修改的是scrape_configs節(jié)點(diǎn)下的配置,這個(gè)節(jié)點(diǎn)時(shí)配置同步任務(wù)的,這里配置一個(gè)任務(wù)為'prometheus',拉取數(shù)據(jù)的路徑為/actuator/prometheus,目標(biāo)host-port為'localhost:9092',也就是cloud-prometheus-sample暴露的prometheus端點(diǎn),Prometheus(軟件)的默認(rèn)啟動(dòng)端口為9090。啟動(dòng)后,同級(jí)目錄下會(huì)生成一個(gè)data目錄,實(shí)際上起到"時(shí)序數(shù)據(jù)庫(kù)"的類(lèi)似作用。訪問(wèn)Prometheus(軟件)的控制臺(tái)http://localhost:9090/targets:

sp-p-5
sp-p-6

Prometheus度量統(tǒng)計(jì)的所有監(jiān)控項(xiàng)可以在http://localhost:9090/graph中查看到。這里可以觀察到HttpCount的統(tǒng)計(jì),但是界面不夠炫酷,配置項(xiàng)也少,因此需要引入Grafana。

安裝和接入Grafana

Grafana的安裝也十分簡(jiǎn)單,它也是開(kāi)箱即用的,就是配置的時(shí)候需要熟悉它的語(yǔ)法。先到Grafana官網(wǎng)下載頁(yè)面下載一個(gè)適合系統(tǒng)的版本,這里選擇Windows版本。解壓之后,直接運(yùn)行bin目錄下的grafana-server.exe即可,默認(rèn)的啟動(dòng)端口是3000,訪問(wèn)http://localhost:3000/,初始化賬號(hào)密碼是admin/admin,首次登陸需要修改密碼,接著添加一個(gè)數(shù)據(jù)源:

sp-p-7

接著添加一個(gè)新的命名為'sample'的Dashboard,添加一個(gè)Graph類(lèi)型的Panel,配置其屬性:

sp-p-8
sp-p-9

A記錄(查詢命令)就是對(duì)應(yīng)http://localhost:9090/graph中的查詢命令的目標(biāo):

sp-p-10

很簡(jiǎn)單,配置完畢之后,就可以看到高大上的統(tǒng)計(jì)圖:

sp-p-11

這里只是介紹了Grafana使用的冰山一角,更多配置和使用命令可以自行查閱它的官方文檔。

原理和擴(kuò)展

原理

下面是Prometheus的工作原理流程圖,來(lái)源于其官網(wǎng):

sp-p-12

在SpringBoot項(xiàng)目中,它的工作原理如下:

sp-p-13

這就是為什么能夠使用Metrics的靜態(tài)方法直接進(jìn)行數(shù)據(jù)統(tǒng)計(jì),因?yàn)镾pring內(nèi)部用MeterRegistryPostProcessor對(duì)Metrics內(nèi)部持有的全局的CompositeMeterRegistry進(jìn)行了合成操作,也就是所有MeterRegistry類(lèi)型的Bean都會(huì)添加到Metrics內(nèi)部持有的靜態(tài)globalRegistry。

擴(kuò)展

下面來(lái)個(gè)相對(duì)有生產(chǎn)意義的擴(kuò)展實(shí)現(xiàn),這篇文章提到SpringCloud體系的監(jiān)控,我們需要擴(kuò)展一個(gè)功能,記錄一下每個(gè)有效的請(qǐng)求的執(zhí)行時(shí)間。添加下面幾個(gè)類(lèi)或者方法:

//注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodMetric {

    String name() default "";

    String description() default "";

    String[] tags() default {};
}
//切面類(lèi)
@Aspect
@Component
public class HttpMethodCostAspect {

    @Autowired
    private MeterRegistry meterRegistry;

    @Pointcut("@annotation(club.throwable.sample.aspect.MethodMetric)")
    public void pointcut() {
    }

    @Around(value = "pointcut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        Method targetMethod = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //這里是為了拿到實(shí)現(xiàn)類(lèi)的注解
        Method currentMethod = ClassUtils.getUserClass(joinPoint.getTarget().getClass())
                .getDeclaredMethod(targetMethod.getName(), targetMethod.getParameterTypes());
        if (currentMethod.isAnnotationPresent(MethodMetric.class)) {
            MethodMetric methodMetric = currentMethod.getAnnotation(MethodMetric.class);
            return processMetric(joinPoint, currentMethod, methodMetric);
        } else {
            return joinPoint.proceed();
        }
    }

    private Object processMetric(ProceedingJoinPoint joinPoint, Method currentMethod,
                                 MethodMetric methodMetric) throws Throwable {
        String name = methodMetric.name();
        if (!StringUtils.hasText(name)) {
            name = currentMethod.getName();
        }
        String desc = methodMetric.description();
        if (!StringUtils.hasText(desc)) {
            desc = name;
        }
        String[] tags = methodMetric.tags();
        if (tags.length == 0) {
            tags = new String[2];
            tags[0] = name;
            tags[1] = name;
        }
        Timer timer = Timer.builder(name).tags(tags)
                .description(desc)
                .register(meterRegistry);
        return timer.record(() -> {
            try {
                return joinPoint.proceed();
            } catch (Throwable throwable) {
                throw new IllegalStateException(throwable);
            }
        });
    }
}
//啟動(dòng)類(lèi)里面添加方法
@SpringBootApplication
@EnableEurekaClient
@RestController
public class SampleApplication {

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

    @MethodMetric
    @GetMapping(value = "/hello")
    public String hello(@RequestParam(name = "name", required = false, defaultValue = "doge") String name) {
        return String.format("%s say hello!", name);
    }
}

配置好Grafana的面板,重啟項(xiàng)目,多次調(diào)用/hello接口:

sp-p-14

后記

如果想把監(jiān)控界面做得更炫酷、更直觀、更詳細(xì),可以先熟悉一下Prometheus的查詢語(yǔ)法和Grafana的面板配置,此外,Grafana或者Prometheus都支持預(yù)警功能,可以接入釘釘機(jī)器人等以便及時(shí)發(fā)現(xiàn)問(wèn)題作出預(yù)警。

參考資料:

本文Demo項(xiàng)目倉(cāng)庫(kù):https://github.com/zjcscut/spring-cloud-prometheus-sample

(本文完)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,253評(píng)論 6 342
  • 在Spring Boot的眾多Starter POMs中有一個(gè)特殊的模塊,它不同于其他模塊那樣大多用于開(kāi)發(fā)業(yè)務(wù)功能...
    程序猿DD閱讀 4,998評(píng)論 3 22
  • 原文鏈接:https://docs.spring.io/spring-boot/docs/1.4.x/refere...
    pseudo_niaonao閱讀 4,881評(píng)論 0 9
  • 和諧寧?kù)o陽(yáng)光灑, 書(shū)香綠植醉氧吧。 公交地鐵補(bǔ)單車(chē), 古城四方分秒達(dá)。
    卡斯特羅梁閱讀 166評(píng)論 0 0

友情鏈接更多精彩內(nèi)容