1.編寫lua腳本my.lua
local key = KEYS[1] --限流KEY(一秒一個)
local limit = tonumber(ARGV[1]) --限流大小
local current = tonumber(redis.call('get', key) or "0")
if current + 1 > limit then --如果超出限流大小
return 0
else --請求數+1,並設置2秒過期
redis.call("INCRBY", key,"1")
redis.call("expire", key,"2")
return 1
end
2.把寫好的lua腳本my.lua放到windows redis目錄下面就是和redis-cli.exe同級目錄
D:\Redis-x64-3.2.100
my.lua
3.打開windows cmd命令窗口執行命令
D:\Redis-x64-3.2.100>redis-cli.exe --eval my5.lua 1 ip:1213 , 5
上面命令解釋來源:https://www.redisgreen.net/blog/intro-to-lua-for-redis-programmers/
redis-cli.exe --eval my5.lua 1 ip:1213 , 5
上面命令中的1表示有幾個key這里只有一個key 所以lua代碼中只能用KEY[1]獲取
KEY[1]=ip:1213
逗號,表示分割KEY和ARGV
再看一個例子:
local link_id = redis.call("INCR", KEYS[1])
redis.call("HSET", KEYS[2], link_id, ARGV[1])
return link_id
redis-cli --eval incrset.lua links:counter links:urls , http://malcolmgladwellbookgenerator.com/
終於在國外一個大神寫的call函數解決我困惑一天的問題
local redis = require 'redis'
-- If you have some different host/port change it here
local host = "127.0.0.1"
local port = 6379
client = redis.connect(host, port)
-- Workaround for absence of redis.call or atelast I did not find one
-- And did not want to digg in redis source code to see how does he get redis.call
redis.call = function(cmd, ...)
return assert(loadstring('return client:'.. string.lower(cmd) ..'(...)'))(...)
end
local r = redis.call('get', 'foo')
print(r)
有個這個call函數就可以方便調試了
有個這個call函數就可以方便調試了
有個這個call函數就可以方便調試了