LUA:解析多行变量并剪切所需的字符串

时间:2018-02-02 15:52:37

标签: nginx lua

我有下一个带有Lua代码的nginx位置(与nginx lua-resty-redis一起使用):

location = /healthcheck {

  content_by_lua_block {

    local red = redis:new()
    used_mem_limit = 536870912

    -- connect to redis
    ok, err = red:connect(ngx.var.redis_host, 6379)
    if not ok then
        ngx.log(ngx.ERR, "Redis connection error: ", err)
        ngx.status = 500
        return
    end

    -- setting connection timeout
    red:set_timeout(1000)

    -- getting redis used_memory_rss
    memory = red:info('memory')

    red_used_memory = ...

    -- set response code
    if (red_used_memory >= used_mem_limit) then
      http_code = 500
    elseif (red_used_memory < used_mem_limit)
      http_code = 200
    else
      http_code = 500
    end

    ngx.status = http_code

  }

}

memory变量应该是这样的:

# Memory
used_memory:105157968
used_memory_human:100.29M
used_memory_rss:110387200
used_memory_rss_human:105.27M
used_memory_peak:105219456
used_memory_peak_human:100.35M
used_memory_peak_perc:99.94%
used_memory_overhead:32290608
used_memory_startup:487168
used_memory_dataset:72867360
used_memory_dataset_perc:69.62%
total_system_memory:1044770816

我需要获得used_memory_rss值,因此我可以将其与used_mem_limit进行比较。所以,我不知道如何完成red_used_memory = ...行。

1 个答案:

答案 0 :(得分:2)

似乎只有可能值的数字,因此请使用简单的正则表达式,然后将结果字符串转换为数字:

red_used_memory = tonumber(memory:match('used_memory_rss:(%d+)'))

换行符无关紧要。