如何在Lua脚本中正确检查Redis键的类型?

ghhaqwfi  于 2023-06-21  发布在  Redis
关注(0)|答案(2)|浏览(132)

在lua脚本中检查redis key类型的正确方法。
我试着把我的头围绕redis lua脚本,我找不到正确的方法来检查什么类型的关键。
以下是我尝试过的:

127.0.0.1:6379> SET test_key test_value
OK
127.0.0.1:6379> GET test_key
"test_value"
127.0.0.1:6379> EVAL 'local type = redis.call("TYPE", KEYS[1]); return type' 1 test_key
string

所以我看到type =“string”,但是:

127.0.0.1:6379> EVAL 'local type = redis.call("TYPE", KEYS[1]); local res; if type == string then res = "ok" else res = "not ok" end return res' 1 test_key
"not ok"
127.0.0.1:6379> EVAL 'local type = redis.call("TYPE", KEYS[1]); local res; if type == string then res = "ok" else res = "not ok" end return res' 1 "test_key"
"not ok"
127.0.0.1:6379> EVAL 'local type = redis.call("TYPE", KEYS[1]); local res; if type == "string" then res = "ok" else res = "not ok" end return res' 1 "test_key"
"not ok"
127.0.0.1:6379> EVAL 'local type = redis.call("TYPE", KEYS[1]); local res; if type == "string" then res = "ok" else res = "not ok" end return res' 1 test_key
"not ok"
qxsslcnc

qxsslcnc1#

我在这里找到了答案:Using the TYPE command inside a Redis / Lua Script
简短的回答是,在lua脚本中redis.call(“TYPE”,key)返回的不是字符串,而是带有key“ok”的lua表,该表保存该类型的字符串值。
因此,要检查密钥的类型,您应该像这样比较:

if redis.call("TYPE", key)["ok"] == "string"

例如:

127.0.0.1:6379> EVAL 'local type = redis.call("TYPE", KEYS[1])["ok"]; local res; if type == "string" then res = "ok" else res = "not ok" end return res' 1 test_key
"ok"
woobm2wo

woobm2wo2#

Lua做得很好,但Redis似乎喜欢数据类型字符串
看看这个

127.0.0.1:6379> SET test_key '{"JSON_KEY": 3.1415926}'
OK
127.0.0.1:6379> eval 'local f = redis.call("GET", KEYS[1]) redis.log(2, f) return(type(f))' 1 test_key
"string"
127.0.0.1:6379> SET test_key 12345
OK
127.0.0.1:6379> eval 'local f = redis.call("GET", KEYS[1]) redis.log(2, f) return(type(f))' 1 test_key
"string"
127.0.0.1:6379>

服务器上的输出

25984:M 02 Jun 2023 19:15:30.677 * {"JSON_KEY": 3.1415926}
25984:M 02 Jun 2023 19:15:47.863 * 12345

相关问题