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

问题是,当脚本返回"tonumber(total)/tonumber(count)"时,它的值总是0,已检查这些键并在redis中存储为字符串的非零值。这个脚本有什么问题?

提前致谢!

点赞
用户1898426
用户1898426

我已经找到答案了,我需要在返回结果之前将其转换为字符串:

    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

希望对某人有所帮助!

2013-04-03 17:25:53