Skip to content

Instantly share code, notes, and snippets.

@gotnix
Last active August 14, 2020 08:28
Show Gist options
  • Save gotnix/bf1c9916c3f1fd11e73ecbba907a7476 to your computer and use it in GitHub Desktop.
Save gotnix/bf1c9916c3f1fd11e73ecbba907a7476 to your computer and use it in GitHub Desktop.
为了测试边缘负载均衡的限流策略,需要灵活的调整真实服务器的 TPS,把 Nginx 配置成一个假负载,可以通过 url 参数 s 传值给 ngx.sleep() 控制后端的响应时间。测试方式:curl http://localhost:80/mock/sleep?s=2
server {
listen 80 backlog=4096 reuseport;
server_name localhost;
index index.html;
root /opt/case/null/;
access_log off;
location /status {
stub_status on;
allow 127.0.0.1;
deny all;
}
location ^~ /mock/sleep {
content_by_lua_block {
require "resty.core"
local arg = ngx.req.get_uri_args()
for k,v in pairs(arg) do
if (k == "s" and tonumber(v) <= 60) then
ngx.sleep(v)
ngx.header["Content-type"] = "text/plain";
ngx.say("Have been sleeping for ", v, " seconds.")
else
ngx.header["Content-type"] = "text/plain";
ngx.say("The value of arguments must be 0.001 ~ 60.")
ngx.say('Usage:')
ngx.say(' curl http://localhost:80/mock/sleep?s=2')
end
end
}
}
}
server {
listen 80 default_server;
return 403;
##. Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
#return 301 https://$host$request_uri;
}
@gotnix
Copy link
Author

gotnix commented Mar 27, 2020

为了防止有人捣蛋,URI 参数 s 的取值范围是 0.001 ~ 60,如果觉得不合适,修改 if 语句的检查条件即可。ngx.sleep() 的单位是秒,精度是毫秒,更多信息请参考:
https://github.com/openresty/lua-nginx-module#ngxsleep
https://moonbingbing.gitbooks.io/openresty-best-practices/ngx_lua/sleep.html
https://blog.cloudflare.com/a-question-of-timing/

测试范例:

# » curl --silent -o /dev/null \
-w "\n\n#-- DNS Lookup --\ntime_namelookup\t: %{time_namelookup}\n\n#-- TCP Handshake --\ntime_connect\t: %{time_connect}\n\n#-- SSL Handshake --\ntime_appconnect\t: %{time_appconnect}\n\ntime_pretransfer\t: %{time_pretransfer}\n#-- Wait Server Response --\ntime_starttransfer\t: %{time_starttransfer}\ntime_redirect\t: %{time_redirect}\n\n#-- Data Transfer --\ntime_total\t: %{time_total}\n" \
'http://localhost:80/mock/sleep?s=2'


#-- DNS Lookup --
time_namelookup : 0.004

#-- TCP Handshake --
time_connect    : 0.004

#-- SSL Handshake --
time_appconnect : 0.000

time_pretransfer        : 0.004
#-- Wait Server Response --
time_starttransfer      : 2.007
time_redirect   : 0.000

#-- Data Transfer --
time_total      : 2.007

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment