Zum Hauptinhalt springen
Chris’ wirre Gedankenwelt
  1. posts/

redis subscribe to key

Redis has a buildin pubsub mechanism, but by default it is not possible to listen on specific keys. Redis 2.8 intruduced Keyspace Notifications , to which you can subscribe.

First of all. This feature is disabled by default, so we need to enable it

$ redis-cli config set notify-keyspace-events KAE

This little python-script listens on keyspace-Events containing stash:silence/*

#!/usr/bin/env python

import redis

r = redis.StrictRedis()

pubsub = r.pubsub()
pubsub.psubscribe('__keyspace@*:stash:silence/*')
for msg in pubsub.listen():
    print(msg)

Results to:

{'pattern': '__keyspace@*:stash:silence/*', 'type': 'pmessage', 'channel': '__keyspace@0__:stash:silence/controller.local/check_instance_snat', 'data': 'expired'}

{'pattern': '__keyspace@*:stash:silence/*', 'type': 'pmessage', 'channel': '__keyspace@0__:stash:silence/compute.local', 'data': 'set'}
{'pattern': '__keyspace@*:stash:silence/*', 'type': 'pmessage', 'channel': '__keyspace@0__:stash:silence/compute.local', 'data': 'expire'}

Why?

We are using sensu for monitoring. If someone press the stash-Button (or creates a stash via the sensu-api) we want to send out an ACK email. The sensu-api only inserts into redis and does not inform anyone about the stash. It would be possible to poll the api peridically, but man... it's 2015.