Created
May 4, 2012 17:58
-
Star
(107)
You must be signed in to star a gist -
Fork
(39)
You must be signed in to fork a gist
A short script exploring Redis pubsub functions in Python
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
import redis | |
import threading | |
class Listener(threading.Thread): | |
def __init__(self, r, channels): | |
threading.Thread.__init__(self) | |
self.redis = r | |
self.pubsub = self.redis.pubsub() | |
self.pubsub.subscribe(channels) | |
def work(self, item): | |
print item['channel'], ":", item['data'] | |
def run(self): | |
for item in self.pubsub.listen(): | |
if item['data'] == "KILL": | |
self.pubsub.unsubscribe() | |
print self, "unsubscribed and finished" | |
break | |
else: | |
self.work(item) | |
if __name__ == "__main__": | |
r = redis.Redis() | |
client = Listener(r, ['test']) | |
client.start() | |
r.publish('test', 'this will reach the listener') | |
r.publish('fail', 'this will not') | |
r.publish('test', 'KILL') |
hi Delsss, what Redis version did you mean?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On some redis version, the client subscriber can't be the same as client publisher, which means:
r = redis.Redis()
client = Listener(redis.Redis(), ["test"])
Is a better version...