Skip to content

Instantly share code, notes, and snippets.

@itamarhaber
Created December 5, 2017 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itamarhaber/11005df3fa21a9b3256416a42c0ace6c to your computer and use it in GitHub Desktop.
Save itamarhaber/11005df3fa21a9b3256416a42c0ace6c to your computer and use it in GitHub Desktop.
Threaded Redis PubSub demonstration in Python w/ redis-py
# Demonstrates PubSub
import threading
import redis
class Listener(threading.Thread):
def __init__(self, r, p):
threading.Thread.__init__(self)
self.redis = r
self.pubsub = self.redis.pubsub()
self.pubsub.psubscribe(p)
def run(self):
for m in self.pubsub.listen():
if 'pmessage' != m['type']:
continue
if '__admin__' == m['channel'] and 'shutdown' == m['data']:
print 'Listener shutting down, bye bye.'
break
print '[{}]: {}'.format(m['channel'], m['data'])
if __name__ == "__main__":
r = redis.StrictRedis()
client = Listener(r, '*')
client.start()
r.publish('channel1', 'message1')
r.publish('channel2', 'message2')
r.publish('channel1', 'message3')
r.publish('__admin__', 'shutdown')
print 'Main ended.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment