Redis整合Lua指令碼實現,redislua指令碼
作者:zhanhailiang 日期:2014-12-02
相關依賴
1. 環境部署
- Redis安裝配置教程及phpredis擴充安裝測試
- Redis安裝以及php擴充
- Windows下安裝phpredis模組(當前Window環境下的php_redis.dll基本還是2.1.3,而Linux下的redis.so版本已經到了2.2.5,這可能導致部分指令集的支援程度不同)
2. Redis指令手冊
- php-redis中文協助手冊.chm(這份手冊相對較舊,請參照Redis Commands)
- Redis Commands
- EVAL script numkeys key [key ...] arg [arg ...]
3. Lua語言基礎
- 《Lua 5.1 參考手冊》雲風 譯
- LUA TABLE 遍曆數組的應用
4. Redis與Lua通訊原理
- Lua: 給 Redis 使用者的入門指導
- Redis新分支,進行服務端lua指令碼支援的開發
- 《Redis 2.6 Lua 指令碼功能實現分析》
整合Lua指令碼操作Redis的優勢
能夠上Redis更快!很多Redis應用的使用方式是read-compute-write模式,這使得一次簡單的資料計算都需要用戶端與服務端進行兩次通訊,而如果把中間的compute過程轉移到服務端執行,則可以成倍地減少round-trip時間。
充分利用CPU!Redis的絕大多數應用情境都是IO密集型,即使是到達CPU100%極限(Redis無法使用多核)的,CPU的使用也大多是在網路通訊協定棧的處理上,但如果使用服務端執行的指令碼,則可以充分將Redis Server的CPU利用起來。
但最根本的原因在於:這樣我們可以只在Redis中實現最基本的能夠滿足99%使用者需求的功能,把其它獨特應用情境下的1%的功能留給自訂的服務端執行指令碼來實現。對於害怕Redis引入服務端指令碼後變得冗餘龐大的同學,看到這裡可以舒一口氣了,因為這就是為了防止滿足無休止的需求而提出的終極解決方案。
原文請見:Redis新分支,進行服務端lua指令碼支援的開發
整合Lua指令碼的弊端(待考證)
- 使用twemproxy作為redis svr代理時由於twemproxy對不完全支援eval,evalSha,可能導致部分相容問題;
- Lua可能會給伺服器帶來額外開銷;
應用原理
Redis實現與Lua指令碼的通訊的方案是通過用戶端將lua指令碼作為命令傳給服務端,服務端讀到指令碼,調用解譯器進行解釋後進行執行並返回來實現。
其提供兩個介面實現:
[root@~/wade/lua/historyBrowsing]# redis-cli 127.0.0.1:6379> help eval EVAL script numkeys key [key ...] arg [arg ...] summary: Execute a Lua script server side since: 2.6.0 group: scripting 127.0.0.1:6379> help evalsha EVALSHA sha1 numkeys key [key ...] arg [arg ...] summary: Execute a Lua script server side since: 2.6.0 group: scripting
接下來通過一個簡單的Demo實現來解釋下其應用情境:
在redis伺服器上儲存了一個key為name2的資料,其儲存結構為zset,此時我們可以通過如下方法訪問:
127.0.0.1:6379> eval 'return redis.call("zrange", "name2", 0 , -1);' 01) "1"
當然以上樣本只是為了說明eval的用法,實際操作時直接redis-client zrang name2 0 -1即可。
但是如果我要求可以動態讀取key來擷取對應的值,此時就需要使用lua指令碼來實現對應的功能。
以下託管於github.com的代碼實現了瀏覽曆史添加功能,有興趣的同學可以學習下,不必在意其中具體的商務邏輯,只需關心redis是如何與lua通訊的即可:
<?php// vim: set expandtab cindent tabstop=4 shiftwidth=4 fdm=marker: /** * @version 1.0 * @author wade * @date 2014-12-01 22:56:38 * @desc redis整合lua指令碼功能實現瀏覽曆史功能 */$redis = new Redis();$redis->connect('127.0.0.1', '6379');// $redis->set('test', 'Hello World');// echo $redis->get('test');$luaScript = file_get_contents('./addItemToBrowsingHistory.lua');$ret = $redis->eval($luaScript, array(4028, 'brand_browsing_10010', 1417498107, 'brand_expired_10010', 1417498107, 1417498107, 3, 1417457308));var_export($ret);$err = $redis->getLastError(); var_export($err);
-- $productId, $browsingKey, $browsingTime, $expiredKey, $expiredTime, $delTime, $maxHistoryLength, $now-- ARGV[1], ARGV[2], ARGV[3], ARGV[4], , ARGV[5], ARGV[6], ARGV[7], ARGV[8]-- 4011, brand_browsing_10010, 1417498107, brand_expired_10010, 1417498107, 1417498107, 3, 1417440107 local productId = ARGV[1];local browsingKey = ARGV[2];local browsingTime = ARGV[3];local expiredKey = ARGV[4];local expiredTime = ARGV[5];local delTime = ARGV[6];local maxHistoryLength = ARGV[7];local now = ARGV[8];local num;local tProductId;local index; redis.call('zAdd', browsingKey, browsingTime, productId);redis.call('expire', browsingKey, delTime); redis.call('zAdd', expiredKey, expiredTime, productId);redis.call('expire', expiredKey, delTime); local count = redis.call('ZCARD', expiredKey);local balance = count - maxHistoryLength;if balance > 0 then -- 擷取到期列表 -- NMB by score local expiredList = redis.call('zRangeByScore', expiredKey, 0, now); if expiredList ~= false and #expiredList ~= 0 then -- 有商品到期 刪除 num = redis.call('zDeleteRangeByScore', expiredKey, 0, now); balance = balance - num; for tProductId in ipairs(expiredList) do redis.call('ZREM', browsingKey, tProductId); end end if balance > 0 then -- 否則判斷瀏覽曆史列表 -- 刪了瀏覽曆史最後一下 local expiredList2 = redis.call('zRange', browsingKey, 0, balance - 1); num = redis.call('zRemRangeByRank', browsingKey, 0, balance - 1); -- NMB by index for index=1, #expiredList2 do redis.call('ZREM', expiredKey, expiredList2[index]); end endend return 0;
源碼請見:https://github.com/billfeller/historyBrowsing