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 ...
随机推荐
- AIDL与service
Service:Local service,一个进程中的多线程服务. AIDL:remote service,不同进程间通信. Service启动方法: startService():调用方destr ...
- 关于开始学习Leetcode的第一帖
从明天开始,白天在实验室完成工作,晚上来图书馆换个环境去学习算法数据结构等计算机基础性的技能.在LeetCode这个平台上做题. 现在感觉自己在算法和数据机构这方面实在是太薄弱了,需要慢慢的捡起来来, ...
- [转]ubuntu 12.04添加launcher方法
[转]ubuntu 12.04添加launcher方法 http://www.cnblogs.com/Jerryshome/archive/2012/08/21/2649500.html 对ubunt ...
- Entity Framework 学习第一天 续
改写第一天的增删改查方法,观察增删改查的本质 using System; using System.Collections.Generic; using System.Data.Entity.Infr ...
- html标记列表应用
一.[ul]无序列表 1.无序列表====== 二.[ol]有序列表 1.有序列表用于段落有序的排列, <ol> <li>内容</li> </ol> 三 ...
- Careercup - Google面试题 - 5424071030341632
2014-05-08 22:55 题目链接 原题: Given a list of strings. Produce a list of the longest common suffixes. If ...
- AxMicrosoft.Office.Interop.Owc11.AxSpreadsheet控件在C#中的引用
这几天要是用AxMicrosoft.Office.Interop.Owc11.AxSpreadsheet控件做查询,发现一系列问题,一点点记录下来吧,以备后查: 第一.相关属性:http://www. ...
- How to Build FFmpeg for Android
http://www.roman10.net/how-to-build-ffmpeg-for-android/ ffmpeg is an open-source platform for record ...
- loadrunner-增加检查点(web_reg_find)
接口性能测试地址: http://192.168.x.x:x/tionWeb/Ajax_GetStock.aspx?stockcode=600571 性能测试脚本: Action() { lr_sta ...
- 【BZOJ】【4034】【HAOI2015】T2
树链剖分/dfs序 树上单点修改+子树修改+链查询 其实用dfs序做也可以…… 其实树链剖分就是一个特殊的dfs序嘛= =所以树链剖分也可以搞子树-(Orz ZYF) 至于为什么……你看在做剖分的时候 ...