Created
November 15, 2014 02:06
-
-
Save korya/158640deed255fcc8da7 to your computer and use it in GitHub Desktop.
Examples of Lua in Redis (http://www.redisgreen.net/library.html); also there is a nice tutorial (http://www.redisgreen.net/blog/intro-to-lua-for-redis-programmers/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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