Redis+Lua的好處
redis在2.6開始加入了lua腳本,使用lua腳本有如下好處:
- 減少網(wǎng)絡開銷。復合操作需要向Redis發(fā)送多次請求,如上例,而是用腳本功能完成同樣的操作只需要發(fā)送一個請求即可,減少了網(wǎng)絡往返時延。
- 原子操作。Redis會將整個腳本作為一個整體執(zhí)行,中間不會被其他命令插入。換句話說在編寫腳本的過程中無需擔心會出現(xiàn)競態(tài)條件,也就無需使用事務。事務可以完成的所有功能都可以用腳本來實現(xiàn)
- 復用。客戶端發(fā)送的腳本會永久存儲在Redis中,這就意味著其他客戶端(可以是其他語言開發(fā)的項目)可以復用這一腳本而不需要使用代碼完成同樣的邏輯
如何使用redis+lua
lua腳本中如何調(diào)用redis的命令
在lua腳本中我們可以使用方法 redis.call('xxx','xxx',...) 和 redis.pcall('xxx','xxx',...) 來通過lua調(diào)用redis的命令
例如下面的命令,通過redis.call來設置name的值并獲取
call()和pcall的區(qū)別:當命令執(zhí)行出錯時redis.pcall會記錄錯誤并繼續(xù)執(zhí)行,而redis.call會直接返回錯誤,不會繼續(xù)執(zhí)行*
#test.lua
redis.call('set','name','gulugulu');
local myName = redis.call('get','name');
return myName;
通過redis-cli客戶端執(zhí)行l(wèi)ua腳本
通過--help我們知道redis的客戶端支持通過--eval來執(zhí)行l(wèi)ua腳本
[root@server-1 bin]# ./redis-cli --help
redis-cli 4.0.14
Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
-h <hostname> Server hostname (default: 127.0.0.1).
...此處省略無關(guān)輸出
--intrinsic-latency <sec> Run a test to measure intrinsic system latency.
The test will run for the specified amount of seconds.
--eval <file> Send an EVAL command using the Lua script at <file>.
--eval格式
KEYS[number] 表示的是redis的key的名稱,ARGV[number]表示參數(shù)的值
沒搞懂為redis要將KEYS和ARGV分開,在我看來直接使用一個就可以了,反正都是入?yún)ⅲ烙嬍菫榱藚^(qū)分
./redis-cli --eval lua腳本的地址 [KEYS[1],KEYS[2]....] , [ARGV[1],ARGV[2]....]
例子
#test.lua
redis.call('set',KEYS[1],ARGV[1]);
redis.call('expire',KEYS[1],ARGV[2]);
local myName = redis.call('get',KEYS[1]);
return myName;
執(zhí)行
[root@server-1 bin]# ./redis-cli -a 123456 --eval test.lua myName , gulugulu 20
"gulugulu"
在redis客戶端里面執(zhí)行l(wèi)ua命令
EVAL命令
格式
注意點: 這個keys的個數(shù)不能省略,假如沒有KEYS入?yún)?shù),要將他設置成0
127.0.0.1:6379> eval "要執(zhí)行的lua命令" key的個數(shù) [KEYS[1]...] [AVRG[1]...]
例子
127.0.0.1:6379> eval "return redis.call('SET',KEYS[1],ARGV[1])" 1 foo bar
OK
127.0.0.1:6379> eval "return redis.call('SET','name','gulugulu')" #沒有寫key個數(shù),程序報錯
(error) ERR wrong number of arguments for 'eval' command
127.0.0.1:6379> eval "return redis.call('SET','name','gulugulu')" 0
OK
EVALSHA命令
上面使用EVAL命令后面帶著lua的腳本命令,考慮到在腳本比較長的情況下,如果每次調(diào)用腳本都需要將這個腳本傳給Redis會占用較多的帶寬。為了解決這個問題,Redis提供了EVALSHA命令允許開發(fā)者通過腳本內(nèi)容的SHA1摘要來執(zhí)行腳本,改命令的用法和EVAL一樣,只不過是將腳本內(nèi)容替換成腳本內(nèi)容的SHA1摘要
先使用SCRIPT LOAD命令將腳本命令轉(zhuǎn)成SHA1
127.0.0.1:6379> SCRIPT LOAD "return redis.call('SET',KEYS[1],ARGV[1])"
"cf63a54c34e159e75e5a3fe4794bb2ea636ee005"
使用SHA1來執(zhí)行
127.0.0.1:6379> evalsha cf63a54c34e159e75e5a3fe4794bb2ea636ee005 1 foo bar
OK
判斷是否有這個SHA1
127.0.0.1:6379> script exists cf63a54c34e159e75e5a3fe4794bb2ea636ee005
1) (integer) 1
清除已經(jīng)加載的SHA1
127.0.0.1:6379> script flush
OK
127.0.0.1:6379> script exists cf63a54c34e159e75e5a3fe4794bb2ea636ee005
1) (integer) 0
強制刪除正在執(zhí)行的腳本,當遇到耗時的lua腳本時可以使用
127.0.0.1:6379> SCRIPT KILL
(error) NOTBUSY No scripts in execution right now.
redis的數(shù)據(jù)類型和lua腳本的數(shù)據(jù)類型互轉(zhuǎn)
因為redis有自己的數(shù)據(jù)類型,lua腳本也有自己的數(shù)據(jù)類型。會使用如下的規(guī)則進行互轉(zhuǎn)
例子
demo1.lua
local status1 = redis.call('SET',"xuzy","xuzy")
return status1['ok']
#這里返回的是表類型,里面就一個ok字段,值為OK
[root@hadoop-master bin]# ./redis-cli --eval demo1.lua
"OK"
lua腳本執(zhí)行的原子性和執(zhí)行時間
Redis的腳本執(zhí)行時原子的,即腳本執(zhí)行期間Redis不會執(zhí)行其他命令,所以使用腳本時要慎用,進行不要執(zhí)行耗時的時間,這樣會導致redis不能執(zhí)行其他操作。為了防止某個腳本執(zhí)行時間過長導致Redis無法提供服務(比如陷入死循環(huán)),Redis提供了lua-time-limit參數(shù)限制腳本的最長運行時間,默認為5秒鐘。但這里并不是說這個腳本被kill掉了,這個配置的意思是5秒后redis會接收其他客戶端發(fā)過來的命令,但腳本還是會繼續(xù)執(zhí)行,為了保護腳本的原子性,其他客戶端命令允許接受,但會返回BUSY錯誤,只有SCRIPT KILL 和SHUTDOWN NOSAVE命令不會發(fā)出錯誤,因為他們是用來停止腳本的
假設上面已經(jīng)在執(zhí)行一個lua腳本了
127.0.0.1:6379> get foo
(error) BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.
redis-cluster下執(zhí)行l(wèi)ua
本中的所有鍵必須在 cluster 中的同一個節(jié)點中。要想讓 script 能在 cluster 下正常工作,必須要把會用到的鍵名明確指出。這樣節(jié)點在收到 eval 命令后就能分析出所要操作的鍵是不是都在一個節(jié)點里了,如果是則正常處理,不是就返回 CROSSSLOT 錯誤。如果不明確指出,比如你的例子,eval 命令發(fā)到了 master1 上,那么讀 key2 時就會報錯了。也就是說,在多節(jié)點集群下執(zhí)行腳本無法保證操作多key的原子性。因為多key如果不在同一個節(jié)點中的話,就會出現(xiàn)CROSSSLOT的錯誤
學習例子
1.Redis腳本實現(xiàn)訪問頻率限制
編寫lua腳本hello.lua
#incr命令當沒有key時候會自動創(chuàng)建且初始值為1
local times = redis.call('incr',KEYS[1])
if times==1 then
redis.call('expire',KEYS[1],ARGV[1])
end
if times > tonumber(ARGV[2]) then
return 0
end
return 1
執(zhí)行
#--eval 后面帶lua文件
#-a 后面帶redis客戶端密碼,如果沒設置則不用
#key和value用逗號分隔,注意逗號之間要兩個空格,這個表示一個key,兩個value
./redis-cli -a 123456 --eval hello.lua rate.limiting:127.0.0.1 , 10 3
運行結(jié)果:
域名rate.limiting:127.0.0.1在10秒內(nèi)限制訪問次數(shù)為3,超過程序返回0
[root@server-1 bin]# ./redis-cli -a 123456 --eval hello.lua rate.limiting:127.0.0.1 , 10 3
Warning: Using a password with '-a' option on the command line interface may not be safe.
(integer) 1
[root@server-1 bin]# ./redis-cli -a 123456 --eval hello.lua rate.limiting:127.0.0.1 , 10 3
Warning: Using a password with '-a' option on the command line interface may not be safe.
(integer) 1
[root@server-1 bin]# ./redis-cli -a 123456 --eval hello.lua rate.limiting:127.0.0.1 , 10 3
Warning: Using a password with '-a' option on the command line interface may not be safe.
(integer) 1
[root@server-1 bin]# ./redis-cli -a 123456 --eval hello.lua rate.limiting:127.0.0.1 , 10 3
Warning: Using a password with '-a' option on the command line interface may not be safe.
(integer) 0
[root@server-1 bin]# ./redis-cli -a 123456 --eval hello.lua rate.limiting:127.0.0.1 , 10 3
Warning: Using a password with '-a' option on the command line interface may not be safe.
(integer) 0
1.Redis腳本實現(xiàn)簡易秒殺
#buy.lua
local buyNum = ARGV[1]
local goodsKey = KEYS[1]
local goodsNum = redis.call('get',goodsKey)
if tonumber(goodsNum) >= tonumber(buyNum) then
redis.call('decrby',goodsKey,buyNum)
return buyNum
else
return '0'
end
@org.junit.Test
public void testByLua2() throws IOException {
JedisConnectionFactory factory = (JedisConnectionFactory) applicationContext.getBean("jedisConnectionFactory");
Jedis jedis = factory.getConnection().getNativeConnection();
jedis.set("shop001","100");
ClassPathResource classPathResource = new ClassPathResource("buy.lua");
String luaString = FileUtils.readFileToString(classPathResource.getFile());
System.out.println(luaString);
for (int i = 0; i < 10; i++) {
String count = (String) jedis.eval(luaString, Lists.newArrayList("shop001"), Lists.newArrayList(String.valueOf(RandomUtils.nextInt(1, 30))));
if(count.equals("0")){
System.out.println("庫存不夠");
break;
}
}
}
redis+lua腳本調(diào)試
在執(zhí)行的腳本上加上--ldb就可以進行調(diào)試
例子
demo1.lua
local status1 = redis.call('SET',"xuzhiyong","xuzhiyong")
redis.debug(status1)
return status1['ok']
[root@hadoop-master bin]# ./redis-cli --ldb --eval demo1.lua