Last active
August 29, 2015 14:10
-
-
Save krist00fer/0d516db1d0a07aa052c6 to your computer and use it in GitHub Desktop.
Sliding window epiration of keys in Redis
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
// Prerequisites: | |
// npm install redis | |
var redis = require('redis'); | |
var client = redis.createClient(); | |
client.setex('fixedexpkey', 5, 'Foo'); | |
client.setex('slidingexpkey', 5, 'Bar'); | |
// Get value every second without using a sliding window expiration implementation | |
setInterval(getStatic, 1000); | |
// Get value every second using custom sliding windows expiration implementation | |
setInterval(getSliding, 1000); | |
function getStatic() { | |
client.get('fixedexpkey', function(err, val) { | |
if (!err) { | |
console.log('fixedexpkey =', val); | |
} | |
}); | |
} | |
function getSliding() { | |
getex('slidingexpkey', 5, function(err, val) { | |
if (!err) { | |
console.log('slidingexpkey =', val); | |
} | |
}); | |
} | |
// Sample implementation of a sliding window expiration | |
// NOTE: You could argue that in reallity you don't need to | |
// GET and EXPIRE your key within a transaction (MULTI) | |
// Most of the time you would probably be fine without | |
function getex(key, seconds, callback) { | |
var multi = client.multi(); | |
multi.get(key); | |
multi.expire(key, seconds); | |
multi.exec(function(err, replies) { | |
if (err) { | |
callback(err); | |
} else { | |
callback(null, replies[0]); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment