引言:"we may deprecate and finally remove transactions" and "everything you can do with a Redis transaction, you can also do with a script"
使用lua腳本的好處
1.lua腳本是作為一個整體執(zhí)行的.所以中間不會被其他命令插入;
2.可以把多條命令一次性打包,所以可以有效減少網(wǎng)絡開銷;
3.lua腳本可以常駐在redis內(nèi)存中,所以在使用的時候,可以直接拿來復用.也減少了代碼量.
例子: 訪問控制 ,10秒內(nèi)最多訪問3次.訪問頻率在10s內(nèi)小于等于3次時返回1,否則返回0
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í)行方式:redis-cli -h 10.10.196.4 -p 7096 -a focus_redis --eval test.lua han1
其中,han1就是KYES[1], KYES和ARGV用逗號分割
ps:lua里面對于數(shù)組 for i,v in ipairs(t) do body end中,i就是數(shù)組下標劝贸,v就是對應的值艰猬,如果是table就是key和value譬挚。table.insert(targetTable, k, v)
lua中引入組件使用十籍,local cjson = require "cjson"愤炸,cjson.encode(數(shù)組或者table),cjson.decode(jsonstring)
搶紅包例子:https://blog.csdn.net/hengyunabc/article/details/19433779/