監(jiān)控方案
Prometheus 實(shí)現(xiàn) OpenResty 的流量監(jiān)控目前有兩個(gè)方案:
- OpenResty 部署虛擬主機(jī)流量統(tǒng)計(jì)模塊 nginx-module-vts,它支持 Prometheus 采集的格式,它能對每個(gè)虛擬主機(jī)進(jìn)行流量統(tǒng)計(jì)。
image.png
- 在 OpenResty 中自己通過 Lua 實(shí)現(xiàn),并通過 nginx-lua-prometheus 庫暴露出指標(biāo)給 Prometheus 采集。
通過 Lua 腳本實(shí)現(xiàn) OpenResty 虛擬主機(jī)流量統(tǒng)計(jì)
流量統(tǒng)計(jì)需要在 OpenResty 的 Log 階段實(shí)現(xiàn),Log 處理階段與流量相關(guān)的變量:
-
$bytes_sent: 流出流量,發(fā)送給客戶端的總字節(jié)數(shù); -
$request_length: 流入流量,請求的長度(包括請求行,請求頭和請求正文);
nginx.conf:
error_log logs/error.log warn;
events {
worker_connections 1024;
}
http {
lua_shared_dict prometheus_metrics 10M;
lua_package_path "lualib/nginx-lua-prometheus/?.lua;;";
init_worker_by_lua_block {
-- 初始化 prometheus
prometheus = require("prometheus").init("prometheus_metrics")
-- 創(chuàng)建 prometheus 指標(biāo)
metric_bandwidth = prometheus:counter("bandwidth",
"Total bandwidth in bytes per virtual host in Nginx",
{"type", "host"}
)
}
log_by_lua_block {
local body_size = ngx.var.bytes_sent
local request_size = ngx.var.request_length
local virtul_host = ngx.var.host
-- 統(tǒng)計(jì) in/out 流量
metric_bandwidth:inc(tonumber(request_size), {"in", virtul_host})
metric_bandwidth:inc(tonumber(body_size), {"out", virtul_host})
}
server {
listen 8080;
location / {
content_by_lua_block {
ngx.say("hello, world")
}
}
}
server {
listen 9145;
allow 127.0.0.1;
deny all;
location /metrics {
content_by_lua_block {
prometheus:collect()
}
}
}
}
這樣就能通過 http://<you_openresty_ip>:9145/metrics 獲取到虛擬主機(jī)流量的相關(guān)指標(biāo)了
總結(jié)
使用 nginx-module-vts 的方法優(yōu)點(diǎn)是不需要自己寫代碼,且功能豐富,不過需要重新編譯安裝 Nginx。使用 nginx-lua-prometheus + Lua 腳本的方式部署相對簡單,且靈活度較高。不過,最終使用那種方案需要根據(jù)當(dāng)前各自的場景,使用之前一定要先壓測!!
