Redis+Lua的好處
redis在2.6開始加入了lua腳本赞赖,使用lua腳本有如下好處:
- 減少網(wǎng)絡(luò)開銷滚朵。復(fù)合操作需要向Redis發(fā)送多次請求,如上例前域,而是用腳本功能完成同樣的操作只需要發(fā)送一個(gè)請求即可辕近,減少了網(wǎng)絡(luò)往返時(shí)延。
- 原子操作话侄。Redis會(huì)將整個(gè)腳本作為一個(gè)整體執(zhí)行亏推,中間不會(huì)被其他命令插入学赛。換句話說在編寫腳本的過程中無需擔(dān)心會(huì)出現(xiàn)競態(tài)條件年堆,也就無需使用事務(wù)。事務(wù)可以完成的所有功能都可以用腳本來實(shí)現(xiàn)
- 復(fù)用盏浇”渖ィ客戶端發(fā)送的腳本會(huì)永久存儲(chǔ)在Redis中,這就意味著其他客戶端(可以是其他語言開發(fā)的項(xiàng)目)可以復(fù)用這一腳本而不需要使用代碼完成同樣的邏輯
如何使用redis+lua
lua腳本中如何調(diào)用redis的命令
在lua腳本中我們可以使用方法 redis.call('xxx','xxx',...) 和 redis.pcall('xxx','xxx',...) 來通過lua調(diào)用redis的命令
例如下面的命令,通過redis.call來設(shè)置name的值并獲取
call()和pcall的區(qū)別:當(dāng)命令執(zhí)行出錯(cuò)時(shí)redis.pcall會(huì)記錄錯(cuò)誤并繼續(xù)執(zhí)行绢掰,而redis.call會(huì)直接返回錯(cuò)誤痒蓬,不會(huì)繼續(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分開滴劲,在我看來直接使用一個(gè)就可以了,反正都是入?yún)⒐ド梗烙?jì)是為了區(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命令
格式
注意點(diǎn): 這個(gè)keys的個(gè)數(shù)不能省略,假如沒有KEYS入?yún)?shù)班挖,要將他設(shè)置成0
127.0.0.1:6379> eval "要執(zhí)行的lua命令" key的個(gè)數(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個(gè)數(shù)鲁捏,程序報(bào)錯(cuò)
(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)用腳本都需要將這個(gè)腳本傳給Redis會(huì)占用較多的帶寬给梅。為了解決這個(gè)問題,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
判斷是否有這個(gè)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
強(qiáng)制刪除正在執(zhí)行的腳本,當(dāng)遇到耗時(shí)的lua腳本時(shí)可以使用
127.0.0.1:6379> SCRIPT KILL
(error) NOTBUSY No scripts in execution right now.
redis的數(shù)據(jù)類型和lua腳本的數(shù)據(jù)類型互轉(zhuǎn)
因?yàn)閞edis有自己的數(shù)據(jù)類型,lua腳本也有自己的數(shù)據(jù)類型渔期。會(huì)使用如下的規(guī)則進(jìn)行互轉(zhuǎn)
例子
demo1.lua
local status1 = redis.call('SET',"xuzy","xuzy")
return status1['ok']
#這里返回的是表類型运吓,里面就一個(gè)ok字段,值為OK
[root@hadoop-master bin]# ./redis-cli --eval demo1.lua
"OK"
lua腳本執(zhí)行的原子性和執(zhí)行時(shí)間
Redis的腳本執(zhí)行時(shí)原子的,即腳本執(zhí)行期間Redis不會(huì)執(zhí)行其他命令,所以使用腳本時(shí)要慎用羽德,進(jìn)行不要執(zhí)行耗時(shí)的時(shí)間几莽,這樣會(huì)導(dǎo)致redis不能執(zhí)行其他操作。為了防止某個(gè)腳本執(zhí)行時(shí)間過長導(dǎo)致Redis無法提供服務(wù)(比如陷入死循環(huán))宅静,Redis提供了lua-time-limit參數(shù)限制腳本的最長運(yùn)行時(shí)間章蚣,默認(rèn)為5秒鐘。但這里并不是說這個(gè)腳本被kill掉了,這個(gè)配置的意思是5秒后redis會(huì)接收其他客戶端發(fā)過來的命令姨夹,但腳本還是會(huì)繼續(xù)執(zhí)行纤垂,為了保護(hù)腳本的原子性,其他客戶端命令允許接受磷账,但會(huì)返回BUSY錯(cuò)誤峭沦,只有SCRIPT KILL 和SHUTDOWN NOSAVE命令不會(huì)發(fā)出錯(cuò)誤,因?yàn)樗麄兪怯脕硗V鼓_本的
假設(shè)上面已經(jīng)在執(zhí)行一個(gè)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 中的同一個(gè)節(jié)點(diǎn)中逃糟。要想讓 script 能在 cluster 下正常工作吼鱼,必須要把會(huì)用到的鍵名明確指出。這樣節(jié)點(diǎn)在收到 eval 命令后就能分析出所要操作的鍵是不是都在一個(gè)節(jié)點(diǎn)里了绰咽,如果是則正常處理菇肃,不是就返回 CROSSSLOT 錯(cuò)誤。如果不明確指出取募,比如你的例子琐谤,eval 命令發(fā)到了 master1 上,那么讀 key2 時(shí)就會(huì)報(bào)錯(cuò)了玩敏。也就是說斗忌,在多節(jié)點(diǎn)集群下執(zhí)行腳本無法保證操作多key的原子性。因?yàn)槎鄈ey如果不在同一個(gè)節(jié)點(diǎn)中的話旺聚,就會(huì)出現(xiàn)CROSSSLOT的錯(cuò)誤
學(xué)習(xí)例子
1.Redis腳本實(shí)現(xiàn)訪問頻率限制
編寫lua腳本hello.lua
#incr命令當(dāng)沒有key時(shí)候會(huì)自動(dòng)創(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客戶端密碼织阳,如果沒設(shè)置則不用
#key和value用逗號(hào)分隔,注意逗號(hào)之間要兩個(gè)空格砰粹,這個(gè)表示一個(gè)key,兩個(gè)value
./redis-cli -a 123456 --eval hello.lua rate.limiting:127.0.0.1 , 10 3
運(yùn)行結(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腳本實(shí)現(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就可以進(jìn)行調(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