一、統(tǒng)計(jì)實(shí)現(xiàn)
js 統(tǒng)計(jì)訪問量,utils.js:
/**
* 查詢?cè)L問總量
*/
function getNum(key) {
let num = ngx.shared.num.get(key);
return num ?? 0;
}
/**
* 記錄訪問量
*/
function record(r, data, flags) {
// 在最后一個(gè)數(shù)據(jù)塊時(shí)增加一次請(qǐng)求數(shù)量
if (flags && flags.last) {
let key = "request_num";
let num = getNum(key);
num++;
// 保存到共享內(nèi)存中
ngx.shared.num.set(key, num);
}
r.sendBuffer(data, flags);
}
function query(r) {
return getNum("request_num");
}
export default { record, query };
nginx 配置:
http {
# 設(shè)置一塊共享內(nèi)存區(qū)域,用于保存請(qǐng)求數(shù)量
js_shared_dict_zone zone=num:512K type=number state=/var/nginx/num.json;
# js文件路徑
js_path "/usr/local/nginx/njs";
# 導(dǎo)入js統(tǒng)計(jì)模塊
js_import utils.js;
server {
listen 89;
server_name localhost;
location / {
# 記錄請(qǐng)求數(shù),其它需要統(tǒng)計(jì)訪問量的location相同配置,js_body_filter指令不能配置中http中
js_body_filter utils.record;
root html;
index index.html index.htm;
}
location /stat {
default_type text/plain;
charset utf-8;
# 統(tǒng)計(jì)接口/stat的訪問沒有計(jì)算到訪問總量中
# js_body_filter utils.record;
# 獲取請(qǐng)求數(shù)總量
js_set $request_num utils.query;
return 200 "總請(qǐng)求量:$request_num";
}
}
}
二、測試
安裝壓測工具, sudo yum install httpd-tools
發(fā)送 200 個(gè)請(qǐng)求, ab -n 200 -c 5 http://localhost:89/
接口查看訪問量, curl http://localhost:89/stat
, 返回 總請(qǐng)求量:200
查看 state 文件中的訪問量,cat /var/nginx/num.json
,返回 {"request_num":{"value":200.000000,"expire":2819531276}}
重啟 nginx 驗(yàn)證,共享數(shù)據(jù)是否仍然存在,reload 后數(shù)據(jù)不會(huì)丟失,stop 再啟動(dòng)數(shù)據(jù)丟失。
三、按客戶端地址統(tǒng)計(jì)訪問量
js 方法中記錄統(tǒng)計(jì)量的 key 改為遠(yuǎn)程地址:
/**
* 查詢?cè)L問總量
*/
function getNum(key) {
let num = ngx.shared.num.get(key);
return num ?? 0;
}
/**
* 記錄訪問量
*/
function record(r, data, flags) {
// 在最后一個(gè)數(shù)據(jù)塊時(shí)增加一次請(qǐng)求數(shù)量
if (flags && flags.last) {
let key = r.variables.remote_addr;
let num = getNum(key);
num++;
// 保存到共享內(nèi)存中
ngx.shared.num.set(key, num);
}
r.sendBuffer(data, flags);
}
export default { record };
獲取統(tǒng)計(jì)量,直接返回 state 對(duì)應(yīng)的 json 文件:
http {
js_shared_dict_zone zone=num:512K type=number state=/var/nginx/stat.json;
js_path "/usr/local/nginx/njs";
js_import utils.js;
server {
listen 89;
server_name localhost;
location / {
# 記錄請(qǐng)求數(shù)
js_body_filter utils.record;
root html;
index index.html index.htm;
}
location /stat {
default_type application/json;
charset utf-8;
alias /var/nginx/;
try_files stat.json '';
}
}
}
四、相關(guān)知識(shí)
閱讀原文:原文鏈接
該文章在 2025/8/25 13:31:23 編輯過