0

我在 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)'
4

1 回答 1

0

根据这个答案和一些测试下一个配置来完成这项工作:

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 >/tmp/ps.out", "w")
        ps:close()
        local ps = io.popen("grep -c '[j]ava.*63' /tmp/ps.out")
        local output = tostring(ps:read())
        ps:close()
        if string.match(output, '4') then
            ngx.status = 200
        else
            ngx.status = 500
        end

    }

}
于 2016-04-19T15:34:02.323 回答