当前位置: 移动技术网 > IT编程>数据库>Redis > Redis和Lua使用过程中遇到的小问题

Redis和Lua使用过程中遇到的小问题

2020年03月09日  | 移动技术网IT编程  | 我要评论
问题 在 redis 里执行 get 或 hget 不存在的 key 或 field 时返回值在终端显式的是 (nil),类似于下面这样 127.0.0.1:6379&

问题

在 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"

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网