版本:自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/