大多数教程中,都只使用了一个健康检查的例子,大部分用户需求是多个upstream配置多个不同的健康检查url,就不知道怎么配置了。
一般教程的健康检查url:
http {
#---------------------
# test health check
#---------------------
lua_package_path "/usr/local/openresty/lualib/resty/?.lua;/usr/local/openresty/lualib/resty/upstream/?.lua;;";
upstream tomcat {
server 127.0.0.1:48080;
server 127.0.0.1:58080;
}
lua_shared_dict healthcheck 1m;
lua_socket_log_errors off;
init_worker_by_lua_block {
local hc = require "resty.upstream.healthcheck"
local ok, err = hc.spawn_checker {
shm = "healthcheck",
upstream = "tomcat",
type = "http",
http_req = "GET /health.txt HTTP/1.0\r\nHost: tomcat\r\n\r\n",
interval = 2000,
timeout = 5000,
fall = 3,
rise = 2,
valid_statuses = {200, 302},
concurrency = 1,
}
if not ok then
ngx.log(ngx.ERR, "=======> failed to spawn health checker: ", err)
return
end
}
server {
listen 38080;
server_name localhost;
access_log logs/access-38080.log main;
error_log logs/error-38080.log debug;
location / {
proxy_pass http://tomcat;
}
location /server/status {
access_log off;
default_type text/plain;
content_by_lua_block {
local hc = require "resty.upstream.healthcheck"
ngx.say("Nginx Worker PID: ", ngx.worker.pid())
ngx.print(hc.status_page())
}
}
}
}
里面的init_worker_by_lua_block 即为一个upstream设置健康检查。
那么如何为多个upstream设置不同的,比如说,我还有一个tomcat2,健康检查为health2。实际上init_worker_by_lua_block相当于一个方法,我们只需要在这个方法中继续为upstream添加checker就行了。
http {
#---------------------
# test health check
#---------------------
lua_package_path "/usr/local/openresty/lualib/resty/?.lua;/usr/local/openresty/lualib/resty/upstream/?.lua;;";
upstream tomcat {
server 127.0.0.1:48080;
server 127.0.0.1:58080;
}
upstream tomcat2 {
server 127.0.0.1:48081;
server 127.0.0.1:58081;
}
lua_shared_dict healthcheck 1m;
lua_socket_log_errors off;
init_worker_by_lua_block {
local hc = require "resty.upstream.healthcheck"
local ok, err = hc.spawn_checker {
shm = "healthcheck",
upstream = "tomcat",
type = "http",
http_req = "GET /health.txt HTTP/1.0\r\nHost: tomcat\r\n\r\n",
interval = 2000,
timeout = 5000,
fall = 3,
rise = 2,
valid_statuses = {200, 302},
concurrency = 1,
}
if not ok then
ngx.log(ngx.ERR, "=======> failed to spawn health checker: ", err)
return
end
local ok, err = hc.spawn_checker {
shm = "healthcheck",
upstream = "tomcat2",
type = "http",
http_req = "GET /health2.txt HTTP/1.0\r\nHost: tomcat\r\n\r\n",
interval = 2000,
timeout = 5000,
fall = 3,
rise = 2,
valid_statuses = {200, 302},
concurrency = 1,
}
if not ok then
ngx.log(ngx.ERR, "=======> failed to spawn tomcat2 health checker: ", err)
return
end
}
server {
listen 38080;
server_name localhost;
access_log logs/access-38080.log main;
error_log logs/error-38080.log debug;
location / {
proxy_pass http://tomcat;
}
location /server/status {
access_log off;
default_type text/plain;
content_by_lua_block {
local hc = require "resty.upstream.healthcheck"
ngx.say("Nginx Worker PID: ", ngx.worker.pid())
ngx.print(hc.status_page())
}
}
}
}
就是这么简单。其实一般仔细看看代码,不难得出配置方法。
看别人踩坑,铺平自己的路,欢迎关注猿界汪汪队;