脚本功能
对Redis中的key进行匹配,如果key存在则进行精准匹配,并获取key对应的value。如果key不存在则进行模糊匹配,并获取模糊匹配到的key对应的value。若精准匹配和模糊匹配都未匹配到key,则返回空字符串。Redis中存储的key及值如下图:
脚本代码
-- 脚本名:keys.lua
redis.replicate_commands()
local FIELD_TEST_INFO = 'test_info'
local test_info = ""
-- local test_key = "test:my_test:iphone11"
-- local test_key = "test:my_test:iphone12"
local test_key = "test:my_test:Andorid"
if 1 == redis.call('exists', test_key) then
test_info = redis.call('hget', test_key, FIELD_TEST_INFO)
else
local keys = redis.call('keys', "test:my_test:iphone*")
for i = 1, #keys
do
local _, s = string.find('test:my_test:iPhone12', keys[i])
if s ~= nil then
test_info = redis.call('hget', keys[i], FIELD_TEST_INFO)
break
end
end
end
return test_info
脚本运行结果
-
当test_key为test:my_test:iphone11时,脚本运行结果如下:
-
当test_key为test:my_test:iphone12时,脚本运行结果如下:
-
当test_key为test:my_test:Andorid时,脚本运行结果如下:
调试
如下命令可将redis执行的命令写入到test.log中,在test.log中可看到脚本的执行过程以便于调试
redis-cli -h 10.1.101.13 -p 6383 -a 19q5#%c@R4*26txt%a -c monitor > test.log