我在 nginx 配置中有 lua 块,它检查 redis-server 连接以及是否有 4 个 java 进程启动,然后根据此检查返回 200 或 500 状态。
location = /healthcheck {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.status = 500
return
end
local ps = io.popen("/bin/ps aux |grep -c '[j]ava.*63'")
local output = tostring(ps:read('*a'))
ps:close()
if string.match(output, '4') then
ngx.status = 200
else
ngx.status = 500
end
}
}
但是周期性output
变量具有nil
价值,而它不应该。只是不明白为什么会这样。
先谢谢各位同志了。
升级版:
使用tonumber
失败
bad argument #2 to 'tonumber' (number expected, got string)
更新位置配置:
location = /healthcheck {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.status = 500
return
end
local ps = io.popen("/bin/ps aux |grep -c '[j]ava.*63'")
local output = tonumber(ps:read())
ps:close()
if (output == 4) then
ngx.status = 200
else
ngx.status = 500
end
}
}
UPD2:
记录到 nginx 错误(使用 tostring)接下来会打印:
grep: write error: Broken pipe
2016/04/19 17:54:48 [error] 301#0: *5 [lua] content_by_lua(healthcheck.conf:33):20: OUTPUT:nil
UPD3:
使用命令grep -c '[j]ava.*63' <(/bin/ps aux)
避免使用管道:
local ps = io.popen("grep -c '[j]ava.*63' <(/bin/ps aux)")
得到下一个错误:
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `grep -c '[j]ava.*63' <(/bin/ps aux)'