1. 程式人生 > >編寫prometheus的client libraries和在Spring boot中的應用

編寫prometheus的client libraries和在Spring boot中的應用

1 編寫client libraries

有一個關鍵的類Collector,它的collect方法返回零個或多個metric指標和樣本。使用CollectorRegister完成Collector註冊,資料通過CollectorRegister暴露給class/method/function,返回prometheus支援的metric格式。每次CollectorRegister被抓取,它必須呼叫每一個Collector的collect方法。
大多數使用者互動的介面,包括Counter、Gauge、Summary、Histogram Collector。

2)Metrics
Counter和Gauge必須是client library的一部分,Summary和Histogram至少提供一個。Metrics建立的示例程式碼如下:

class YourClass {
  static final Counter requests = Counter.build()
      .name("requests_total")
      .help("Requests.").register();
}

以上將把requests指標註冊到預設的CollectorRegistry。
Counter是單調增加的計數器,不允許減少值,且必須有以下的方法:

  • inc():增加1
  • Inc(double v):增加給定的值,必須大於等於0

Gauge(計量儀)代表值可以變大變小,必須有以下的方法:
Inc()/inc(double v)/dec()/dec(double v)/set(double v)
Summary:通過滑動時間視窗觀察Summary樣本,並提供給例項觀察他們的分佈、頻率和求和。必須有以下的方法:

  • Observe(double v):觀察給定的次數。

Histogram允許聚合事件的分佈,比如請求延時。一旦metric被建立,Buckets不能改變。Histogram必須有以下的方法:

  • Boserve(double v):觀察給定的次數。

3)Labels
Labels是prometheus最有強大的方面,但是容易忽略。對於client library必須關心labels如何提供給users。

2 Spring boot中prometheus的使用

1)使用maven構建工程,引入以下依賴項

<dependency>
   <groupId
>
io.prometheus</groupId> <artifactId>simpleclient_spring_boot</artifactId> <version>0.0.26</version> </dependency>

在入口類添加註解 @EnablePrometheusEndpoint,另外由於依賴項會預設啟用Actuator的security安全認證機制,因此在工程的application配置中需要把它disable掉,配置項為management.security.enabled=false。
2)定義指標類,並設定相關的labelNames,並定義指標的相關操作,程式碼示例如下:

@Component
public class CustomMetric {
    static final Counter requests = Counter.build().name("my_request_total").help("Total request.")
            .labelNames("method").register();
    public void processRequest(String method){
        requests.labels(method.toUpperCase()).inc();
    }
}

這裡的關鍵是Counter型指標的例項化方法,注意build()和register()的用法。
3)在指標的收集處,根據要收集指標的邏輯呼叫相應指標的操作方法,從而完成指標值的收集工作,示例程式碼如下:

@RestController
public class MainController {

    @Autowired
    CustomMetric customMetric;

    @Autowired
    HttpServletRequest request;

    @RequestMapping(value="/")
    public String home(){
        customMetric.processRequest(request.getMethod());
        return "Hello world!";
    }
}

這裡主要是對request請求的次數進行計數,同時記錄請求呼叫的method型別。
4)下載prometheus,通過配置prometheus.yml檔案,修改targets和metrics_path路徑。需要注意的是通過以上方式的完成metrics指標的自定義和收集,指標資料預設暴露在相應服務的/prometheus,因此配置檔案修改如下所示(部分配置):

    metrics_path: '/prometheus'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ['localhost:8090']

5)啟動prometheus服務,訪問9090埠能夠檢視相應的指標資料。這裡有簡單的query查詢框和可用指標的下拉選擇框,下拉選擇框中包括了targets中可用的指標資料。同時有時間序列的影象化簡單展示,截圖如下:
prometheus-ui 簡易的管理查詢頁面
6)記錄每一個請求的相關資訊,這裡可以使用filter來截獲請求,然後更新相關的指標,示例程式碼如下:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    //記錄每一個請求的相關資訊
    HttpServletRequest request = (HttpServletRequest)servletRequest;
    customMetric.processRequest(request.getMethod(), request.getRequestURI());
    filterChain.doFilter(servletRequest, servletResponse);
}