1.tornado队列的特点

和python标准队列queue相比,tornado的队列Queue支持异步

2.Queue常用方法

Queue.get()

会暂停,直到queue中有元素

Queue.put()

对有最大长度限制的队列,会暂停,直到队列有空闲空间

Queue.task_done()

对每一个get元素,紧接着调用task_done(),表示这个任务执行完毕

Queue.join()

等待,直到所有任务都执行完毕,即所有元素都调用了task_done()

3.示例

给出一个地址http://www.tornadoweb.org/en/stable/,分析页面中所有以这个url为前缀的链接,

并依次访问,解析,直到找出所有的url

#!/usr/bin/env python

import time
from datetime import timedelta try:
from HTMLParser import HTMLParser
from urlparse import urljoin, urldefrag
except ImportError:
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag from tornado import httpclient, gen, ioloop, queues base_url = 'http://www.tornadoweb.org/en/stable/'
concurrency = 10 @gen.coroutine
def get_links_from_url(url):
"""Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made
absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes
'http://www.tornadoweb.org/en/stable/gen.html'.
"""
try:
response = yield httpclient.AsyncHTTPClient().fetch(url)
print('fetched %s' % url) html = response.body if isinstance(response.body, str) \
else response.body.decode()
urls = [urljoin(url, remove_fragment(new_url))
for new_url in get_links(html)]
except Exception as e:
print('Exception: %s %s' % (e, url))
raise gen.Return([]) raise gen.Return(urls) def remove_fragment(url):
pure_url, frag = urldefrag(url)
return pure_url def get_links(html):
class URLSeeker(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.urls = [] def handle_starttag(self, tag, attrs):
href = dict(attrs).get('href')
if href and tag == 'a':
self.urls.append(href) url_seeker = URLSeeker()
url_seeker.feed(html)
return url_seeker.urls @gen.coroutine
def main():
q = queues.Queue()
start = time.time()
fetching, fetched = set(), set() @gen.coroutine
def fetch_url():
current_url = yield q.get()
try:
if current_url in fetching:
return print('fetching %s' % current_url)
fetching.add(current_url)
urls = yield get_links_from_url(current_url)
fetched.add(current_url) for new_url in urls:
# Only follow links beneath the base URL
if new_url.startswith(base_url):
yield q.put(new_url) finally:
q.task_done() @gen.coroutine
def worker():
while True:
yield fetch_url() q.put(base_url) # Start workers, then wait for the work queue to be empty.
for _ in range(concurrency):
worker()
yield q.join(timeout=timedelta(seconds=300))
assert fetching == fetched
print('Done in %d seconds, fetched %s URLs.' % (
time.time() - start, len(fetched))) if __name__ == '__main__':
import logging
logging.basicConfig()
io_loop = ioloop.IOLoop.current()
io_loop.run_sync(main)

运行结果:

fetching http://www.tornadoweb.org/en/stable/

fetched http://www.tornadoweb.org/en/stable/

......

fetched http://www.tornadoweb.org/en/stable/_modules/index.html

fetched http://www.tornadoweb.org/en/stable/_modules/tornado/util.html

Done in 11 seconds, fetched 122 URLs.

使用yield,当队列有元素时,q.get()会执行

for _ in range(concurrency): worker()

可以大幅提高效率,原因在于get_links_from_url网络IO会占用较多执行时间,多个异步任务可以并行访问网络io,大大提高了效率。

q.join()会阻塞主程序,直到队列所有的任务都执行完毕

Tornado使用-队列Queue的更多相关文章

  1. Python进阶【第二篇】多线程、消息队列queue

    1.Python多线程.多进程 目的提高并发 1.一个应用程序,可以有多进程和多线程 2.默认:单进程,单线程 3.单进程,多线程 IO操作,不占用CPU python的多线程:IO操作,多线程提供并 ...

  2. Java中的队列Queue,优先级队列PriorityQueue

    队列Queue 在java5中新增加了java.util.Queue接口,用以支持队列的常见操作.该接口扩展了java.util.Collection接口. Queue使用时要尽量避免Collecti ...

  3. jquery 的队列queue

    使用示列代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www ...

  4. Windows Azure Service Bus (2) 队列(Queue)入门

    <Windows Azure Platform 系列文章目录> Service Bus 队列(Queue) Service Bus的Queue非常适合分布式应用.当使用Service Bu ...

  5. Windows Azure Service Bus (3) 队列(Queue) 使用VS2013开发Service Bus Queue

    <Windows Azure Platform 系列文章目录> 在之前的Azure Service Bus中,我们已经介绍了Service Bus 队列(Queue)的基本概念. 在本章中 ...

  6. (C#)使用队列(Queue)解决简单的并发问题

    (C#)使用队列(Queue)解决简单的并发问题 2015-07-16 13:04 13265人阅读 评论(8) 收藏 举报  分类: Asp.Net(8)  版权声明:本文为博主原创文章,未经博主允 ...

  7. STL中的单向队列queue

    转载自:http://blog.csdn.net/morewindows/article/details/6950917 stl中的queue指单向队列,使用时,包含头文件<queue>. ...

  8. java09 队列Queue与Deque

    队列Queue与Deque. Enumeration Hashtable与Hashtable子类Properties(资源配置文件) 引用类型(强.软.弱.虚)与WeakHashMap Identit ...

  9. 队列Queue和栈

    1.队列Queue是常用的数据结构,可以将队列看成特殊的线性表,队列限制了对线性表的访问方式,只能从线性表的一段添加(offer)元素, 从另一段取出(poll)元素,队列遵循先进先出的原则. 2.J ...

随机推荐

  1. SpringBoot与Dubbo整合的三种方式

    1. 使用默认application.properties和注解的方式 导入dubbo-starter,在application.properties配置属性,使用@Service注解来暴露服务,使用 ...

  2. Python 由list转为dictionary

    Python 由list转为dictionary 例如: 原始的 list 形式为: session_item_data=[[100, [10, 11], [12, 13]], [101, [11, ...

  3. Linux运维工程师面试-部分题库

    一.Linux操作系统知识 1.常见的Linux发行版本都有什么?你最擅长哪一个?它的官网网站是什么?说明你擅长哪一块?   2.Linux开机启动流程详细步骤是什么?系统安装完,忘记密码如何破解? ...

  4. wxml

    <template name="objectCombine"> <view> <text> {{for}} </text> < ...

  5. Android上实现MVP模式的途径

    今天我想分享我在Android上实现MVP(Model-View-Presenter)模式的方法.如果你对MVP模式还不熟悉,或者不了解为什么要在Android应用中使用MVP模式,推荐你先阅读这篇维 ...

  6. 【Android】Android动态加载Jar、APK的实现

    本文介绍Android中动态加载Jar.APK的实现.而主要用到的就是DexClassLoader这个类.大家都知道Android和普通的Java虚拟机有差别,它只能加载经过处理的dex文件.而加载这 ...

  7. GIF Brewery for Mac(录制 Gif 动图工具)安装

    1.软件简介    GIF Brewery 一款用于录制 Gif 动图等的工具. 2.资源列表 链接 提取密码 系统要求 软件语言 GIF Brewery for Mac v3.9.5 ltmf ma ...

  8. Mac 常用软件推荐

    1.常用软件推荐 这里推荐的 apps 在开发者圈子内普遍评价不错,能便利的处理日常的开发和使用的任务.以下推荐分为四类: 开发者工具 生产力工具 办公工具 其他 2.Developer Tools ...

  9. Digital Color Meter 颜色值提取工具

    1.Digital Color Meter 简介 Digital Color Meter 是一款 Mac 自带的颜色值提取工具. 其它下载地址 Digital Color Meter for Mac, ...

  10. ConcurrentHashMap vs Collections.synchronizedMap()不同

    之前项目中,有用到过Collections.synchronizedMap(),后面发现当并发数很多的时候,出现其他请求等待情况,因为synchronizedMap会锁住所有的资源,后面通过查阅资料, ...