问题
在 Redis 里执行 get 或 hget 不存在的 key 或 field 时返回值在终端显式的是 (nil),类似于下面这样
127.0.0.1:6379> get test_version (nil)
如果在 Lua 脚本中判断获取到的值是否为空值时,就会产生比较迷惑的问题,以为判断空值的话就用 nil 就可以了,然鹅事实却并不是这样的,如下所示:
127.0.0.1:6379> get test_version (nil) 127.0.0.1:6379> EVAL "local a = redis.call('get',KEYS[1]) print(a) if a == 'nil' then return 1 else return 0 end" 1 test_version test_version (integer) 0
我们来看下执行 Lua 脚本返回结果的数据类型是什么
127.0.0.1:6379> get test_version (nil) 127.0.0.1:6379> EVAL "local a = redis.call('get',KEYS[1]) return type(a)" 1 test_version test_version "boolean"
通过上面的脚本可以看到,当 Redis 返回的结果为 (nil) 时候,其真实的数据类型为 boolean,因此我们直接判断 nil 是有问题的。
Redis 官方文档
通过翻阅官方文档,找到下面所示的一段话,
Redis to Lua conversion table.
- Redis integer reply -> Lua number
- Redis bulk reply -> Lua string
- Redis multi bulk reply -> Lua table (may have other Redis data types nested)
- Redis status reply -> Lua table with a single ok field containing the status
- Redis error reply -> Lua table with a single err field containing the error
- Redis Nil bulk reply and Nil multi bulk reply -> Lua false boolean type
Lua to Redis conversion table.
- Lua number -> Redis integer reply (the number is converted into an integer)
- Lua string -> Redis bulk reply
- Lua 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 reply
- Lua table with a single err field -> Redis error reply
- Lua boolean false -> Redis Nil bulk reply.
解决方案
通过官方文档,我们知道判断 Lua 脚本返回空值使用,应该直接判断 true/false,修改判断脚本如下所示
127.0.0.1:6379> get test_version (nil) 127.0.0.1:6379> EVAL "local a = redis.call('get',KEYS[1]) if a == false then return 'empty' else return 'not empty' end" 1 test_version test_version "empty"
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Redis和Lua使用过程中遇到的小问题”评论...
更新日志
2024年05月10日
2024年05月10日
- 罗大佑.2022-安可曲【种子音乐】【FLAC分轨】
- 《真人快打1》“祖国人”先导预告:开打前先喝奶
- 民主的胜利!Steam开始为《地狱潜者2》超2小时玩家退款
- 《地狱潜者2》鼓励玩家打差评:这样就能和索尼谈判
- 林忆莲《十年珍藏》[WAV分轨][668M]
- 蔡琴《蔡琴经典歌曲合集》[WAV+CUE][502.6MB]
- 群星《十大发烧·靓绝男声》 3CD[APE+CUE][1.1G]
- 彭正.2024-十年【福茂】【FLAC分轨】
- 李健.2005-为你而来【泰达】【WAV+CUE】
- 韩宝仪.2003-柔情恋歌精典2CD【南方】【WAV+CUE】
- 物华弥新迷踪盘第二十六关怎么过 迷踪盘第二十六关通关方法
- 物华弥新迷踪盘第二十七关怎么过 迷踪盘第二十七关通关方法
- 物华弥新迷踪盘第二十五关怎么过 迷踪盘第二十五关通关方法
- 吴克群2015-数星星的人2CD[华纳][WAV+CUE]
- 陈升.2023-望乡【新乐园】【WAV+CUE】