如何异步使用Tornado和Redis? [英] How can I use Tornado and Redis asynchronously?

查看:326
本文介绍了如何异步使用Tornado和Redis?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到如何异步使用Redis和Tornado的方法.我找到了 tornado-redis ,但我不仅需要在代码中添加yield.

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.

我有以下代码:

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()

/wait中有待处理的请求时,我需要访问/网址并获取"Hello World". 我该怎么办?

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?

推荐答案

您不应在Tornado主线程中使用Redis pub/sub,因为它会阻塞IO循环.您可以在主线程中处理来自Web客户端的长时间轮询,但是您应该创建一个单独的线程来侦听Redis.然后,当您收到消息时,可以使用ioloop.add_callback()和/或threading.Queue与主线程进行通信.

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.

这篇关于如何异步使用Tornado和Redis?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆