I want to use redis' pubsub to transmit some messages, but don't want be blocked using listen
, like the code below:
import redis
rc = redis.Redis()
ps = rc.pubsub()
ps.subscribe(['foo', 'bar'])
rc.publish('foo', 'hello world')
for item in ps.listen():
if item['type'] == 'message':
print item['channel']
print item['data']
The last for
section will block. I just want to check if a given channel has data, how can I accomplish this? Is there a check
like method?
If you're thinking of non-blocking, asynchronous processing, you're probably using (or should use) asynchronous framework/server.
if you're using Tornado, there is Tornado-Redis. It's using native Tornado generator calls. Its Websocket demo provides example on how to use it in combination with pub/sub.
if you're using Twisted, there is txRedis. There you also have pub/sub example.
it also seems that you can use Redis-py combined with Gevent with no problems using Gevent's monkey patching (gevent.monkey.patch_all()
).
UPDATE: It's been 5 years since the original answer, in the mean time Python got native async IO support. There now is AIORedis, an async IO Redis client.