问题
在 Redis 里执行 get 或 hget 不存在的 key 或 field 时返回值在终端显式的是 (nil),类似于下面这样
如果在 Lua 脚本中判断获取到的值是否为空值时,就会产生比较迷惑的问题,以为判断空值的话就用 nil 就可以了,然鹅事实却并不是这样的,如下所示:
我们来看下执行 Lua 脚本返回结果的数据类型是什么
通过上面的脚本可以看到,当 Redis 返回的结果为 (nil) 时候,其真实的数据类型为 boolean,因此我们直接判断 nil 是有问题的。
Redis 官方文档
通过翻阅官方文档,找到下面所示的一段话,
Redis to Lua conversion table.
Redis integer reply -> Lua numberRedis bulk reply -> Lua stringRedis multi bulk reply -> Lua table (may have other Redis data types nested)Redis status reply -> Lua table with a single ok field containing the statusRedis error reply -> Lua table with a single err field containing the errorRedis Nil bulk reply and Nil multi bulk reply -> Lua false boolean typeLua to Redis conversion table.
Lua number -> Redis integer reply (the number is converted into an integer)Lua string -> Redis bulk replyLua table (array) -> Redis multi bulk reply (truncated to the first nil inside the Lua array if any)Lua table with a single ok field -> Redis status replyLua table with a single err field -> Redis error replyLua boolean false -> Redis Nil bulk reply.解决方案
通过官方文档,我们知道判断 Lua 脚本返回空值使用,应该直接判断 true/false,修改判断脚本如下所示
关注我们
微信搜索:代码星冰乐,关注我们,每天为你分享方方面面的技术内容~