Created
December 5, 2017 15:38
-
-
Save itamarhaber/11005df3fa21a9b3256416a42c0ace6c to your computer and use it in GitHub Desktop.
Threaded Redis PubSub demonstration in Python w/ redis-py
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
# 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