Lua脚本在Redis中如何计算并返回平均值?
- 内容介绍
- 文章标签
- 相关推荐
本文共计266个文字,预计阅读时间需要2分钟。
我正在Redis中使用LUA脚本查询已存在的两个键(XXX_COUNT和XXX_TOTAL)的除法结果,如果任一键不存在则返回0。脚本代码如下:
lualocal count=redis.call(GET, KEYS[1] .. '_COUNT')local total=redis.call(GET, KEYS[1] .. '_TOTAL')
if count and total then return tonumber(count) / tonumber(total)else return 0end
我正在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中存储为非零值非零值.这个脚本有什么问题?
提前致谢!
我找到了解决方案,我需要在返回之前将结果转换为字符串: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
希望它能帮助别人!
本文共计266个文字,预计阅读时间需要2分钟。
我正在Redis中使用LUA脚本查询已存在的两个键(XXX_COUNT和XXX_TOTAL)的除法结果,如果任一键不存在则返回0。脚本代码如下:
lualocal count=redis.call(GET, KEYS[1] .. '_COUNT')local total=redis.call(GET, KEYS[1] .. '_TOTAL')
if count and total then return tonumber(count) / tonumber(total)else return 0end
我正在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中存储为非零值非零值.这个脚本有什么问题?
提前致谢!
我找到了解决方案,我需要在返回之前将结果转换为字符串: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
希望它能帮助别人!

