Skip to content

Instantly share code, notes, and snippets.

@korya
Created November 15, 2014 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korya/158640deed255fcc8da7 to your computer and use it in GitHub Desktop.
Save korya/158640deed255fcc8da7 to your computer and use it in GitHub Desktop.
-- http://www.redisgreen.net/library/ratelimit.html
-- Return Value: 1 if rate limit exceeded, otherwise 0
-- Keys: 1
-- 1. A key to use as an expiring counter, e.g. "ratelimit:ip:127.0.0.1"
-- Args: 2
-- 1. Maximum number of calls
-- 2. Amount of time in ms
local cnt = redis.call('INCR', KEYS[1])
if cnt > tonumber(ARGV[1])
then
return 1
end
if cnt == 1
then
redis.call('PEXPIRE', KEYS[1], ARGV[2])
end
return 0
-- http://www.redisgreen.net/library/runningavg.html
-- Return Value: the new average value
-- Keys: 2
-- 1. Key to store the current average.
-- 2. Key to store the current count of values.
-- Args: 1
-- 1. The next value in the series
local currentval = tonumber(redis.call('get', KEYS[1])) or 0
local count = redis.call('incr', KEYS[2])
currentval = tostring(currentval * (count - 1)/count + (ARGV[1]/count))
redis.call('set', KEYS[1], currentval)
return currentval
-- http://www.redisgreen.net/library/smemhashes.html
-- Return Value: Multi-Bulk - a list of hashes by key
-- Caveat: This script violates the EVAL command semantics and should not be considered safe for Redis Cluster.
-- Keys: 1
-- 1. A Set containing the keys of a series of Hashes.
-- Args: None
local keys = redis.call("smembers", KEYS[1])
local ret = {}
for k,v in pairs(keys) do
ret[k] = {v, redis.call("hgetall", v)}
end
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment