Redis使用lua腳本

版本:自2.6.0起可用。
時間複雜度:取決於執行的腳本。php

使用Lua腳本的好處:html

  • 減小網絡開銷。能夠將多個請求經過腳本的形式一次發送,減小網絡時延。
  • 原子操做。redis會將整個腳本做爲一個總體執行,中間不會被其餘命令插入。所以在編寫腳本的過程當中無需擔憂會出現競態條件,無需使用事務。
  • 複用。客戶端發送的腳本會永久存在redis中,這樣,其餘客戶端能夠複用這一腳本而不須要使用代碼完成相同的邏輯。

如何使用

基本使用

命令格式: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

  • eval 後面參數是lua腳本文件,.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腳本實現了,運行過程當中確保不會被其它客戶端打斷。

phpredis裏使用

接着上面的例子:

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/

相關文章
相關標籤/搜索