redis - how to get tornadoredis listen value -
i want write chat demo tornado , redis. use redis subscribe , wrote not work . when run code , iterm output
listening 8000 groupchat here getmsg here none none
and publish testc helloword in redis-cli, iterm output:
[i 150401 18:30:57 web:1825] 304 /groupchat?key=testc (127.0.0.1) 2.40ms message(kind=u'message', channel=u'testc', body=u'helloword', pattern=u'testc')
i want message in groupchat.get , none. me?
groupchat code here :
class groupchat(tornado.web.requesthandler): def initialize(self): print 'groupchat here' self.c = tornadoredis.client(host=config['redis_host'], port=config['redis_port'], password=config['redis_auth']) self.channelmsgmodel = channelmsgmodel(self.c) @tornado.gen.coroutine def get(self): try: key = self.get_argument('key') info = yield self.channelmsgmodel.getmsg(key) print info self.finish(info) except exception, e: print e pass
channelmsgmodel code here :
import tornado.gen
class channelmsgmodel : timeout = 10 def __init__(self, redisobj): self.redisobj = redisobj @tornado.gen.coroutine def getmsg(self, key): print 'getmsg here' yield tornado.gen.task(self.redisobj.subscribe, key) info = self.redisobj.listen(self.on_message) print info raise tornado.gen.return(info) def on_message(self, msg): if (msg.kind == 'message'): print msg return msg elif (msg.kind == 'unsubscribe'): self.redisobj.disconnect() # raise tornado.gen.return(false)
use toro.queue (which included in tornado in upcoming version 4.2):
class channelmsgmodel: def __init__(self, redisobj): self.redisobj = redisobj self.queue = toro.queue() @gen.coroutine def getmsg(self, key): yield gen.task(self.redisobj.subscribe, key) self.redisobj.listen(self.on_message) info = yield self.queue.get() raise tornado.gen.return(info) def on_message(self, msg): if (msg.kind == 'message'): self.queue.put_nowait(msg) elif (msg.kind == 'unsubscribe'): self.redisobj.disconnect()
Comments
Post a Comment