getHandel redis,如何异步使用Tornado和Redis?

I'm trying to find how can I use Redis and Tornado asynchronously. I found the tornado-redis but I need more than just add a yield in the code.

I have the following code:

import redis

import tornado.web

class WaiterHandler(tornado.web.RequestHandler):

@tornado.web.asynchronous

def get(self):

client = redis.StrictRedis(port=6279)

pubsub = client.pubsub()

pubsub.subscribe('test_channel')

for item in pubsub.listen():

if item['type'] == 'message':

print item['channel']

print item['data']

self.write(item['data'])

self.finish()

class GetHandler(tornado.web.RequestHandler):

def get(self):

self.write("Hello world")

application = tornado.web.Application([

(r"/", GetHandler),

(r"/wait", WaiterHandler),

])

if __name__ == '__main__':

application.listen(8888)

print 'running'

tornado.ioloop.IOLoop.instance().start()

I need getting access the / url and get the "Hello World" while there's a request pending in the /wait.

How can I do it?

解决方案

You should not use Redis pub/sub in the main Tornado thread, as it will block the IO loop. You can handle the long polling from web clients in the main thread, but you should create a separate thread for listening to Redis. You can then use ioloop.add_callback() and/or a threading.Queue to communicate with the main thread when you receive messages.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值