Redis 與 Lua 使用中的小問題
阿新 • • 發佈:2019-12-31
問題
在 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"
複製程式碼