通过 Prometheus 实现 OpenResty 的流量监控

监控方案

Prometheus 实现 OpenResty 的流量监控目前有两个方案:

  1. OpenResty 部署虚拟主机流量统计模块 nginx-module-vts,它支持 Prometheus 采集的格式,它能对每个虚拟主机进行流量统计。
image.png
  1. 在 OpenResty 中自己通过 Lua 实现,并通过 nginx-lua-prometheus 库暴露出指标给 Prometheus 采集。

通过 Lua 脚本实现 OpenResty 虚拟主机流量统计

流量统计需要在 OpenResty 的 Log 阶段实现,Log 处理阶段与流量相关的变量:

  • $bytes_sent: 流出流量,发送给客户端的总字节数;
  • $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")
        -- 创建 prometheus 指标
        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
        -- 统计 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 获取到虚拟主机流量的相关指标了

总结

使用 nginx-module-vts 的方法优点是不需要自己写代码,且功能丰富,不过需要重新编译安装 Nginx。使用 nginx-lua-prometheus + Lua 脚本的方式部署相对简单,且灵活度较高。不过,最终使用那种方案需要根据当前各自的场景,使用之前一定要先压测!!

参考

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容