如何解决Redis和Lua使用过程中遇到的问题

30次阅读
没有评论

共计 1617 个字符,预计需要花费 5 分钟才能阅读完成。

这篇文章主要介绍如何解决 Redis 和 Lua 使用过程中遇到的问题,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

问题

在 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 

以上是“如何解决 Redis 和 Lua 使用过程中遇到的问题”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注丸趣 TV 行业资讯频道!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-04发表,共计1617字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)