龙卷风异步HTTP客户块
问题描述:
theQueue = tornado.queues.Queue()
theQueue.put_nowait('http://www.baidu.com')
theQueue.put_nowait('http://www.google.com')
theQueue.put_nowait('http://cn.bing.com/')
@tornado.gen.coroutine
def Test1():
def cb(response):
print str(response)
while True:
item = yield theQueue.get()
print item
tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True)
tmp.fetch(item,callback=cb)
@tornado.gen.coroutine
def Test2():
while True:
item = yield theQueue.get()
print item
tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True)
response = yield tmp.fetch(item)
print str(response)
#Test1()
Test2()
tornado.ioloop.IOLoop.instance().start()
蟒2.6和4.2龙卷风
在功能测试1,它将首先打印出3项,然后打印3级的响应。
但是在Test2中,它会打印项目并且它是一个接一个的响应。龙卷风异步HTTP客户块
我很困惑,为什么Test2不是异步?
答
Test2()是异步的,但采用不同的方式,协程的方式。
Tornado的协同程序在它遇到yield
关键字时暂停,等待异步进程(在您的情况下,通过http客户端请求网页)完成。 当前协程暂停时,龙卷风将切换到其他可用协程。
使用协程,您的代码看起来是同步的,并且“同步运行”(如果只有一个协程)。
您可以轻松地测试龙卷风的协程的异步功能,通过使用两个或更多conroutines:
@tornado.gen.coroutine
def Test2():
while True:
item = yield theQueue.get()
print 'Test2:', item
tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True)
response = yield tmp.fetch(item)
print 'Test2:', str(response)
# Write another test function called `Test3` and do the exactly same thing with Test2.
@tornado.gen.coroutine
def Test3():
while True:
item = yield theQueue.get()
print 'Test3:', item
tmp = tornado.httpclient.AsyncHTTPClient(force_instance=True)
response = yield tmp.fetch(item)
print 'Test3:', str(response)
Test2()
Test3()
tornado.ioloop.IOLoop.instance().start()
你会看到的Test2和Test3的同时运行(但不是真的)在这个例子中。
在不同的例程之间切换来执行并发操作的能力,这就是协同异步的含义。
在我的情况下,该队列有很多项目,如果我使用yield,我需要创建多个Test2? –
@JianNiu尝试调用'tornado.ioloop.IOLoop.current()。spawn_callback(Test2)'多次,这将在后台产生多协程。相关文档:http://www.tornadoweb.org/en/stable/guide/coroutines.html#running-in-the-background – piglei