1 編寫client libraries
參考網址:https://github.com/prometheus/client_java
1)整體的結構
有一個關鍵的類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中可用的指標數據。同時有時間序列的圖像化簡單展示,截圖如下:
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);
}