Redis 与 Lua 使用中的小问题

Redis 与 Lua 使用中的小问题-原文连接
redis

问题

在 Redis 里执行 gethget 不存在的 keyfield 时返回值在终端显式的是 (nil),相似于下面这样bash

127.0.0.1:6379> get test_version
(nil)
复制代码

若是在 Lua 脚本中判断获取到的值是否为空值时,就会产生比较迷惑的问题,觉得判断空值的话就用 nil 就能够了,然鹅事实却并非这样的,以下所示:ide

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 脚本返回结果的数据类型是什么ui

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 是有问题的。spa

Redis 官方文档

经过翻阅官方文档,找到下面所示的一段话,code

Redis to Lua conversion table.cdn

  • 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,修改判断脚本以下所示get

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"
复制代码

关注咱们

关注咱们
相关文章
相关标签/搜索