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 ...
随机推荐
- [Java][RCP] 记 ProgressView的使用
进度条效果图
- python2 编码问题详解
实例对比 定义 type str unicode print encode('utf8') decode('utf8') encode('unicode-escape') encode('string ...
- hdu 5249 KPI
题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5249 KPI Description 你工作以后, KPI 就是你的全部了. 我开发了一个服务,取得了 ...
- LD_PRELOAD
下面的helloworld会在屏幕上打印出什么内容? 1 2 3 4 5 6 #include <stdio.h> int main(int argc, char* argv[], cha ...
- php读取xml文件内容,并循环写入mysql数据库
<?php $dbconn = mysql_connect("localhost","root","root"); $db = mys ...
- java判断某个字符串包含某个字符串的个数
/** * 判断str1中包含str2的个数 * @param str1 * @param str2 * @return counter */ public static int countStr(S ...
- Xcode 7遇到 App Transport Security has blocked a cleartext HTTP 错误
今天用Xcode 7 创建新项目用到 URL 发送请求时,报下面的错: “App Transport Security has blocked a cleartext HTTP (http://) r ...
- why does angular js rock
angularjs 入门教程 http://angular-tips.com/blog/2013/08/why-does-angular-dot-js-rock/ Practive the previ ...
- 四则运算三+psp0级表格
一.题目 在四则运算二的基础上,选择一个方向进行拓展,我选择的是增加了答题模块 二.设计思路 1.在上次的基础上,增加了答题模块,每出现一道四则运算题目,便提醒输入结果,如果结果错误,就会提示错误 2 ...
- hibernate 注解写在哪?
是写在get方法上还是 还是成员变量上? 一般 成员变量是私有的,如果写在成员变量上,那么hibernate就能过通过反射机制直接访问到私有变量,破坏了数据的封装性: 所以 :推荐写在方法上,虽然写的 ...