Redis keyspace notifications – Get notified once keys get expired using Jedis

As covered in previous articles redis is a distributed cache/database solution which can be primarily used for caching purpose. Ofter we will have a requirement where we will like to get notified for any cache related events like new addition to cache, deletion from cache or most importantly keys getting expired.

Well, all this is possible in redis and we can show an example using jedis (redis client for java language).

By default these event notifications are disabled. To enable them modify the redis conf file like this :

# By default all notifications are disabled because most users don’t need
# this feature and the feature has some overhead. Note that if you don’t
# specify at least one of K or E, no events will be delivered.
notify-keyspace-events KEA

By default value of notify-keyspace-events would be an empty string which means disabled.

Let’s define the the listener now :

class RedisListener extends JedisPubSub {
 
	@Override
	public void onPSubscribe(String pattern, int subscribedChannels) {
		System.out
				.println("onPSubscribe " + pattern + " " + subscribedChannels);
	}
 
	@Override
	public void onPMessage(String pattern, String channel, String message) {
 
		System.out.println("onPMessage pattern " + pattern + " " + channel
				+ " " + message);
	}
}

Next we need to define a subscriber who would be listening to the events using the above defined listener

package Cache;
 
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
 
public class RedisSubscriber {
	public static void main(String[] args) {
		JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
		Jedis jedis = pool.getResource();
		jedis.psubscribe(new RedisListener(), "__key*__:RT*");
	}
}

Lastly lets write a test program :

public class RedisListenerExample {
	public static void main(String[] args) {
		JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
 
		Jedis jedis = new Jedis("localhost");
		jedis.set("RTnotify", "umq");
		jedis.set("notify", "umq");
		jedis.set("notify1", "umq");
		jedis.set("RTnotify1", "umq");
		jedis.expire("RTnotify", 10); // in Seconds
		System.out.println(jedis.get("notify"));
	}
}

Output of above code would be :

onPSubscribe __key*__:RT* 1
onPMessage pattern __key*__:RT* __keyspace@0__:RTnotify set
onPMessage pattern __key*__:RT* __keyspace@0__:RTnotify1 set
onPMessage pattern __key*__:RT* __keyspace@0__:RTnotify expire
onPMessage pattern __key*__:RT* __keyspace@0__:RTnotify expired

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *