Redis集群Lua函数报错:attempt to compare nil with number排查
问题原因
你遇到的错误是因为tonumber(keyGet)可能返回nil,导致currentValue变成nil,后续和数字5比较时触发类型不匹配错误。
具体来说:当timeSlotKey对应的键存在,但存储的值不是合法的数字字符串(比如是"abc"、空字符串或其他非数字格式),tonumber()转换失败就会返回nil。你的代码只处理了keyGet为nil(键不存在)的情况,却没处理转换失败的场景,这时候currentValue就会被赋值为nil,进而触发比较错误。
修正方案
需要在转换后检查tonumber的结果是否有效,确保currentValue始终为数字类型。修改后的代码如下:
local keyGet = redis.call('GET', timeSlotKey) local currentValue = 0 if keyGet ~= nil then local numValue = tonumber(keyGet) -- 只有转换成功才赋值,否则保持0 currentValue = numValue or 0 end redis.log(redis.LOG_NOTICE, currentValue) if currentValue < 5 then redis.call('INCR', timeSlotKey) redis.call('EXPIRE', timeSlotKey, expiryDuration) return 1 else return 0 end
关键改进点
- 新增
numValue变量存储转换结果,通过or 0确保当转换失败时,currentValue仍为0 - 保证
currentValue始终是数字类型,彻底避免后续比较时的类型错误
另外从业务角度建议:如果这个键是专门用来计数的,最好确保只有通过INCR、SET等命令写入数字格式的值,避免出现非数字值的情况,从根源减少这类问题。
内容的提问来源于stack exchange,提问作者RRM
相关产品推荐
相关产品推荐

