Python异步IO --- 轻松管理10k+并发连接
点击(此处)折叠或打开
- import argparse
- import asyncio
- import functools
- import logging
- import random
- import urllib.parse
- loop = asyncio.get_event_loop()
- @asyncio.coroutine
- def print_http_headers(no, url, keepalive):
- url = urllib.parse.urlsplit(url)
- wait_for = functools.partial(asyncio.wait_for, timeout=3, loop=loop)
- query = ('HEAD {url.path} HTTP/1.1\r\n'
- 'Host: {url.hostname}\r\n'
- '\r\n').format(url=url).encode('utf-8')
- rd, wr = yield from wait_for(asyncio.open_connection(url.hostname, 80))
- while True:
- wr.write(query)
- while True:
- line = yield from wait_for(rd.readline())
- if not line: # end of connection
- wr.close()
- return no
- line = line.decode('utf-8').rstrip()
- if not line: # end of header
- break
- logging.debug('(%d) HTTP header> %s' % (no, line))
- yield from asyncio.sleep(random.randint(1, keepalive//2))
- @asyncio.coroutine
- def do_requests(args):
- conn_pool = set()
- waiter = asyncio.Future()
- def _on_complete(fut):
- conn_pool.remove(fut)
- exc, res = fut.exception(), fut.result()
- if exc is not None:
- logging.info('conn#{} exception'.format(exc))
- else:
- logging.info('conn#{} result'.format(res))
- if not conn_pool:
- waiter.set_result('event loop is done')
- for i in range(args.connections):
- fut = asyncio.async(print_http_headers(i, args.url, args.keepalive))
- fut.add_done_callback(_on_complete)
- conn_pool.add(fut)
- if i % 10 == 0:
- yield from asyncio.sleep(0.01)
- logging.info((yield from waiter))
- def main():
- parser = argparse.ArgumentParser(description='asyncli')
- parser.add_argument('url', help='page address')
- parser.add_argument('-c', '--connections', type=int, default=1,
- help='number of connections simultaneously')
- parser.add_argument('-k', '--keepalive', type=int, default=60,
- help='HTTP keepalive timeout')
- args = parser.parse_args()
- logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
- loop.run_until_complete(do_requests(args))
- loop.close()
- if __name__ == '__main__':
- main()
- # ../sbin/nginx
- # ps ax | grep nginx
- 2007 ? Ss 0:00 nginx: master process ../sbin/nginx
- 2008 ? S 0:00 nginx: worker process
- $ python asyncli.py http://10.211.55.8/ -c 10000
- # tail -1000000 access.log | awk '{ print $4 }' | sort | uniq -c | awk '{ cnt+=1; sum+=$1 } END { printf "avg = %d\n", sum/cnt }'
- avg = 548
- VIRT RES SHR S %CPU %MEM TIME+ COMMAND
- 657m 115m 3860 R 60.2 6.2 4:30.02 python
- 54208 10m 848 R 7.0 0.6 0:30.79 nginx
Python异步IO --- 轻松管理10k+并发连接的更多相关文章
- python异步IO编程(一)
python异步IO编程(一) 基础概念 协程:python generator与coroutine 异步IO (async IO):一种由多种语言实现的与语言无关的范例(或模型). asyncio ...
- python异步IO编程(二)
python异步IO编程(二) 目录 开门见山 Async IO设计模式 事件循环 asyncio 中的其他顶层函数 开门见山 下面我们用两个简单的例子来让你对异步IO有所了解 import asyn ...
- Python - 异步IO\数据库\队列\缓存
协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程,协程一定是在单线程运行的. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和 ...
- Python异步IO
在IO操作的过程中,当前线程被挂起,而其他需要CPU执行的代码就无法被当前线程执行了. 我们可以使用多线程或者多进程来并发执行代码,为多个用户服务. 但是,一旦线程数量过多,CPU的时间就花在线程切换 ...
- Python异步IO之协程(一):从yield from到async的使用
引言:协程(coroutine)是Python中一直较为难理解的知识,但其在多任务协作中体现的效率又极为的突出.众所周知,Python中执行多任务还可以通过多进程或一个进程中的多线程来执行,但两者之中 ...
- python -- 异步IO 协程
python 3.4 >>> import asyncio >>> from datetime import datetime >>> @asyn ...
- python 异步IO
参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143208573 ...
- Python 异步IO、IO多路复用
事件驱动模型 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...
- Day10 - Python异步IO、Pymysql、paramiko、
IO多路复用: 参考博客:http://www.cnblogs.com/wupeiqi/p/6536518.html socket客户端(爬虫): http://www.cnblogs.com/w ...
随机推荐
- poj 2046 Gap
题目连接 http://poj.org/problem?id=2046 Gap Description Let's play a card game called Gap. You have 28 c ...
- uva 11922 Permutation Transforme/splay tree
原题链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=18902 伸展树的区间翻转剪切... 如下: #include< ...
- 切换两个activity
下面是一个切换两个activity是过度动画效果实例:(注意里面的overridePendingTransition()方法)Java代码 1. @Override public void onCre ...
- 一个.net程序员教你使用less
我是一个.net 程序员,虽然说一直做后台,但是web 前端也会去学,虽然说技术只是层窗户纸,但是像我这种多动症患者,不捅破我心难受啊! 好!废话不多提,下面直接正题,至于less 是什么这里不多讲因 ...
- ASP.NET MVC4 View层_Razor操作Html元素
1 常用 Html 标签 1.1 Label Html 语法 :<label for="UserName">用户名</label> Razor语法:@Htm ...
- sublime mac快捷键
^是control ⌥是option 打开/前往 ⌘T 前往文件 ⌘⌃P 前往项目 ⌘R 前往 method ⌘⇧P 命令提示 ⌃G 前往行 ⌘KB 开关侧栏 ⌃ ` python 控制台 ⌘⇧N 新 ...
- 【AFNetworking】AFNetworking源码阅读(一)
1. 前言 2. iOS Example代码结构 3.AFNetworkActivityIndicatorManager 4. UIRefreshControl+AFNetworking 5. AFN ...
- MySQL 存储过程学习笔记
存储过程框架 DEMILITER $$ -- 重定义符 DROP PROCEDURE IF EXISTS store_procedure$$ -- 如果存在此名的存储过程,先删除 CREATE PRO ...
- 【BZOJ 1997】[Hnoi2010]Planar
Description Input Output 找到哈密尔顿环之后找到不在哈密尔顿环上的边 这些边如果同时在里面相交那他们同时在外面也相交,所以只能一外一内,这就变成了2-SAT,判一下就好了 ...
- liferay7中如何Hiding the default Success Message
下面介绍如何把在Liferay 7中如何把action执行成功之后的信息不显示,因为宝宝有需要,就去查了相关源码和资料. 如果想要某个portlet不显示执行成功的信息,在doProcessActio ...