版本:自2.6.0起可用。
時間複雜度:取決於執行的腳本。php
使用Lua腳本的好處:html
命令格式:redis
EVAL script numkeys key [key ...] arg [arg ...]
說明:數組
script
是第一個參數,爲Lua 5.1腳本。該腳本不須要定義Lua函數(也不該該)。numkeys
指定後續參數有幾個key。key [key ...]
,是要操做的鍵,能夠指定多個,在lua腳本中經過KEYS[1]
, KEYS[2]
獲取arg [arg ...]
,參數,在lua腳本中經過ARGV[1]
, ARGV[2]
獲取。簡單實例:bash
127.0.0.1:6379> eval "return ARGV[1]" 0 100 "100" 127.0.0.1:6379> eval "return {ARGV[1],ARGV[2]}" 0 100 101 1) "100" 2) "101" 127.0.0.1:6379> eval "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 key2 first second 1) "key1" 2) "key2" 3) "first" 4) "second" 127.0.0.1:6379> eval "redis.call('SET', KEYS[1], ARGV[1]);redis.call('EXPIRE', KEYS[1], ARGV[2]); return 1;" 1 test 10 60 (integer) 1 127.0.0.1:6379> ttl test (integer) 59 127.0.0.1:6379> get test "10"
注:網絡
{}
在lua裏是指數據類型table
,相似數組。redis.call()
能夠調用redis命令。若是直接使用redis-cli
命令,格式會有點不同:函數
redis-cli --eval lua_file key1 key2 , arg1 arg2 arg3
注意的地方:ui
.lua
後綴numkeys
,而是使用,
隔開。注意,
先後有空格。示例:lua
incrbymul.lua.net
local num = redis.call('GET', KEYS[1]); if not num then return 0; else local res = num * ARGV[1]; redis.call('SET',KEYS[1], res); return res; end
命令行運行:
$ redis-cli --eval incrbymul.lua lua:incrbymul , 8 (integer) 0 $ redis-cli incr lua:incrbymul (integer) 1 $ redis-cli --eval incrbymul.lua lua:incrbymul , 8 (integer) 8 $ redis-cli --eval incrbymul.lua lua:incrbymul , 8 (integer) 64 $ redis-cli --eval incrbymul.lua lua:incrbymul , 2 (integer) 128
因爲redis沒有提供命令能夠實現將一個數原子性的乘以N倍,這裏咱們就用Lua腳本實現了,運行過程當中確保不會被其它客戶端打斷。
接着上面的例子:
incrbymul.php
<?php $lua = <<<EOF local num = redis.call('GET', KEYS[1]); if not num then return 0; else local res = num * ARGV[1]; redis.call('SET',KEYS[1], res); return res; end EOF; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $ret = $redis->eval($lua, array("lua:incrbymul", 2), 1); echo $ret;
運行:
$ redis-cli set lua:incrbymul 0 OK $ redis-cli incr lua:incrbymul (integer) 1 $ php incrbymul.php 2 $ php incrbymul.php 4
eval原型:
Redis::eval(string script, [array keys, long num_keys])
eval函數的第3個參數爲KEYS個數,phpredis依據此值將KEYS和ARGV作區分。
一、在redis中使用lua腳本讓你的靈活性提升5個逼格 - 一線碼農 - 博客園
https://www.cnblogs.com/huang...
二、Redis執行Lua腳本示例 - yanghuahui - 博客園
https://www.cnblogs.com/yangh...
三、EVAL - Redis
https://redis.io/commands/eval
四、phpredis 執行LUA腳本的例子 - jingtan的專欄 - CSDN博客
https://blog.csdn.net/jingtan...
五、lua-book
http://me.52fhy.com/lua-book/