Hello:
在balancer_by_lua_block中,可以通过set_more_tries增加重试次数。而在nginx的ngx_http_proxy_module中
有一个设置选项 proxy_next_upstream_tries控制最大重试次数,默认值是0, 如果已失败次数+set_more_tries的次数超过proxy_next_upstream_)tries的值时,
结果变得十分古怪,甚至出现无限次的重试。
如下面的配置,nginx会一直重试下去。
daemon off;
master_process off;
events {
worker_connections 1024;
}
http {
lua_package_path "/usr/local/nginx/lua-resty-core/lib/?.lua;;";
upstream backend {
server 1.1.1.1:8080;
balancer_by_lua_block {
local balancer = require "ngx.balancer"
balancer.set_more_tries(2)
balancer.set_current_peer('127.0.0.1', '8080')
}
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_next_upstream_tries 5;
}
}
}
或许实际应用中不应该每次都调用set_more_tries来改变重试次数, 只是很奇怪为什么会出现这种情形,
于是研究了下lua-nginx-module的实现,在调用set_more_tries时实际调用的是ngx_http_lua_balancer.c文件中的
ngx_http_lua_ffi_balancer_set_more_tries函数,主要逻辑如下所示
#if (nginx_version >= 1007005)
max_tries = r->upstream->conf->next_upstream_tries;
if (bp->total_tries + count > max_tries) {
count = max_tries - bp->total_tries;
*err = "reduced tries due to limit";
} else {
*err = NULL;
}
#else
*err = NULL;
#endif
bp->more_tries = count;
其中bp->total_tries为当前是第几次尝试连接,count为set_more_tries的参数, max_tries为proxy_next_upstream_tries设置的值。
最终bp->more_tries为最终将要增加的重试次数。因为count为int类型,而bp->more_tries为无符号整数,当count为负时转换为
无符号整数便会非常大,导致重试次数远远超过proxy_next_upstream_tries的限制。
这里是否应该增加判断,当bp->total_tries大于等于max_tries时直接把bp->more_tries设为零,不再增加重试次数。