Emulation of expiration of the set members
Suppose you have some keys and put expiration on some of them. Then you organize them into a set (bucket). Problem that will happen is when a key expires, it is still in the set.
Sure program can handle the expired keys and remove it from the set, however if the key never need it, it will be never removed. Soon after, the set may grow and get all memory available.
First way of dealing with this could be a crontab process that inspects the set element by element and removes them if needed.
Another more tricky way will be to use sorted set.
- If the element have no expiration we set score 0.
- If the element have expiration we set score current_timestamp() + expiration in seconds.
Then prior get the element or range from the sorted set, we do "ZREMRANGEBYSCORE xxx 0 current_timestamp().
Here are the PHP code:
$r = new Redis(); $r->connect("127.0.0.1", "6379"); $key = "myzset"; //Add something... $r->zadd($key, 0, "someting without expiration"); $r->zadd($key, time() + 60 * 5, "someting with 5 min expiration"); // ... // Get element... // ... but remove junk first... $r->zremrangebyscore($key, 0, time()); // ... and get the elements... print_r($r->zrange(0, -1));
Redis connection note
The example uses generic connection to the Redis server. To make the example work with our service you will need to use code similar to this one:
// change these parameter according to the information in your instance list $host = '22.214.171.124'; $port = 1234; $password = 'somehashcode'; $db = 0; $r = new Redis(); $r->connect($host, $port); $r->auth($password); $r->select($db);
blog comments powered by Disqus
Because we want this page to be useful for memcached users, we tagged with memcached all examples that may be "recreated" for memcached server.
How to use Redis for cache MySQL queries in a way similar to memcached
How to use Redis to prevent web-scraping parsing and web-spam
How to do 'Rotating' news list
How pool random element from news list
How Redis can help us with Accounting / Vote / Like / Recommend / +1 clicks
How to implement fast hi-score table
How to scale Redis on several servers using sharding
How to implement distributed work pool and to scale some work across many computers
How to collect and store information for page visitors
How to make set members to expire
How Redis can help us with user level locks
Creating distributed message queue
Building reverse index using sets
Using Redis to speed up MySQL inserts
Using Redis for caching MySQL or Cassandra data inserts
How to produce 'There are 123 visitors on this page' sign