Redis脚本返回平均值

Ser*_*rán 5 lua redis

我正在redis中编写LUA脚本以返回已存储的两个键(XXX_COUNT和XXX_TOTAL)的除法结果,如果任何键不存在则返回0.脚本的代码如下:

    local count = redis.call("GET", KEYS[1]..'_COUNT')
    local total = redis.call("GET", KEYS[1]..'_TOTAL')
    if not count or not total then
        return 0
    else
        return tonumber(total)/tonumber(count)
    end
Run Code Online (Sandbox Code Playgroud)

问题是,当脚本返回"tonumber(total)/ tonumber(count)"时,它的值始终为0,已经检查了键,并且它们在redis中存储为非零值非零值.这个脚本有什么问题?

提前致谢!

Ser*_*rán 5

我找到了解决方案,我需要在返回之前将结果转换为字符串:

    local count = redis.call("GET", KEYS[1]..'_COUNT')
    local total = redis.call("GET", KEYS[1]..'_TOTAL')
    if not count or not total then
        return 0
    else
        local avg = tonumber(total)/tonumber(count)
        return tostring(avg)
    end
Run Code Online (Sandbox Code Playgroud)

希望它对某人有帮助!