示例工程 32-openresty-and-redis

32-openresty-and-redis/03-redis-rate-limit/main.lua

lua · 0.9 KB

-- @runtimes lua54
--- 演示:用 redis.call stub 做固定窗口限流。
local M = {}
 
local function allow(redis, key, limit)
	local count = redis.call("INCR", key)
	if count == 1 then
		redis.call("EXPIRE", key, 60)
	end
	return count <= limit, count
end
 
--- @return table { first = boolean, second = boolean, third = boolean }
function M.run(log)
	log = log or print
	local store = {}
	local redis = {
		call = function(command, key, _arg)
			if command == "INCR" then
				store[key] = (store[key] or 0) + 1
				return store[key]
			elseif command == "EXPIRE" then
				return 1
			end
			return 0
		end,
	}
	local first = allow(redis, "rate:user", 2)
	local second = allow(redis, "rate:user", 2)
	local third = allow(redis, "rate:user", 2)
	log(("first=%s second=%s third=%s"):format(tostring(first), tostring(second), tostring(third)))
	return { first = first, second = second, third = third }
end
if not ... then
	M.run()
end
return M