佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Redis和Lua使用過程中遇到的小問題

Redis和Lua使用過程中遇到的小問題

熱門標(biāo)簽:Linux服務(wù)器 服務(wù)外包 鐵路電話系統(tǒng) 呼叫中心市場需求 AI電銷 網(wǎng)站排名優(yōu)化 地方門戶網(wǎng)站 百度競價排名

問題

在 Redis 里執(zhí)行 get 或 hget 不存在的 key 或 field 時返回值在終端顯式的是 (nil),類似于下面這樣

127.0.0.1:6379> get test_version
(nil)

如果在 Lua 腳本中判斷獲取到的值是否為空值時,就會產(chǎn)生比較迷惑的問題,以為判斷空值的話就用 nil 就可以了,然鵝事實(shí)卻并不是這樣的,如下所示:

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

我們來看下執(zhí)行 Lua 腳本返回結(jié)果的數(shù)據(jù)類型是什么

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"

通過上面的腳本可以看到,當(dāng) Redis 返回的結(jié)果為 (nil) 時候,其真實(shí)的數(shù)據(jù)類型為 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 腳本返回空值使用,應(yīng)該直接判斷 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"

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。

您可能感興趣的文章:
  • 詳解利用redis + lua解決搶紅包高并發(fā)的問題
  • 簡介Lua腳本與Redis數(shù)據(jù)庫的結(jié)合使用
  • Redis執(zhí)行Lua腳本的好處與示例代碼
  • redis中如何使用lua腳本讓你的靈活性提高5個逼格詳解
  • 利用Lua定制Redis命令的方法詳解
  • Redis如何使用lua腳本實(shí)例教程
  • Nginx利用Lua+Redis實(shí)現(xiàn)動態(tài)封禁IP的方法
  • 詳解Redis中Lua腳本的應(yīng)用和實(shí)踐
  • 通過redis的腳本lua如何實(shí)現(xiàn)搶紅包功能

標(biāo)簽:黃山 仙桃 湖南 衡水 蘭州 湘潭 崇左 銅川

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Redis和Lua使用過程中遇到的小問題》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    邢台市| 广平县| 且末县| 陵水| 高清| 吴旗县| 简阳市| 招远市| 德惠市| 鄂温| 广饶县| 阜平县| 宝鸡市| 化德县| 温泉县| 新乡县| 大同县| 永兴县| 简阳市| 迭部县| 吉安市| 象州县| 田东县| 长岛县| 凤山县| 大悟县| 贵德县| 保靖县| 彰化市| 黄龙县| 平塘县| 高唐县| 望都县| 西贡区| 白沙| 巴彦淖尔市| 江都市| 三穗县| 霸州市| 桃源县| 江口县|