当前位置:网站首页>Execute Lua script in redis

Execute Lua script in redis

2022-06-26 10:30:00 Xianghan collection

Redis In the implementation of Lua Script

grammar :

grammar : eval script numkeys keys args

Parameters : eval — redis Provide parsing lua The command of the script

script — lua Script

numkeys — Specify the key name parameter set (keys) The number of

keys — Key name parameter set , adopt Global variables KEYS An array of said , Starting subscript is 1

args — Key value parameter set , Through global variables ARGV Array Express , Starting subscript is 1

Case study :

#  Sign in redis Set a value after 
set kojon 10

To write lua Script

adopt key Multiply the value of by a value

KEYS[1]: Parameters 1, Express key

KEYS[2]: Parameters 2, Express multiple

 local curval =redis.call("get",KEYS[1])
if curval==false then
	curval=0
else
   curval=tonumber(curval)
end 
curval=curval * tonumber(KEYS[2])
redis.call("set",KEYS[1],curval)
return curval

perform

#  grammar  redis-cli -a auth --eval lua file   Parameters 1  Parameters 2
#  No password -a auth
/usr/local/redis/bin/redis-cli -a KS6IxTDg7Q1gqhnWec9s --eval multiply.lua kojon 2

result

shell /usr/local/redis/bin/redis-cli -a KS6IxTDg7Q1gqhnWec9s --eval jisuan.lua kojon 2
(integer) 20

describe : EVAL The semantics of the command requires that the literal quantity should not be written directly in lua Script , It is recommended to use variables to define lua Script , And put the literal in the key name parameter set keys And key value parameter set args in , Through global variables KEYS and ARGV To get , The advantage of this is that it can be cached ! stay lua Script , You can use two functions to perform redis command , Namely :redis.call() and redis.pcall()

原网站

版权声明
本文为[Xianghan collection]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260940305169.html