快來學(xué)學(xué)Python異步IO,輕松管理10k+并發(fā)連接
異步操作在計(jì)算機(jī)軟硬件體系中是一個(gè)普遍概念,根源在于參與協(xié)作的各實(shí)體處理速度上有明顯差異。軟件開發(fā)中遇到的多數(shù)情況是CPU與IO的速度不匹配,所以異步IO存在于各種編程框架中,客戶端比如瀏覽器,服務(wù)端比如node.js。本文主要分析Python異步IO。
Python 3.4標(biāo)準(zhǔn)庫(kù)有一個(gè)新模塊asyncio,用來支持異步IO,不過目前API狀態(tài)是provisional,意味著不保證向后兼容性,甚至可能從標(biāo)準(zhǔn)庫(kù)中移除(可能性極低)。如果關(guān)注PEP和Python-Dev會(huì)發(fā)現(xiàn)該模塊醞釀了很長(zhǎng)時(shí)間,可能后續(xù)有API和實(shí)現(xiàn)上的調(diào)整,但毋庸置疑asyncio非常實(shí)用且功能強(qiáng)大,值得學(xué)習(xí)和深究。
示例
asyncio主要應(yīng)對(duì)TCP/UDP socket通信,從容管理大量連接,而無需創(chuàng)建大量線程,提高系統(tǒng)運(yùn)行效率。此處將官方文檔的一個(gè)示例做簡(jiǎn)單改造,實(shí)現(xiàn)一個(gè)HTTP長(zhǎng)連接benchmark工具,用于診斷WEB服務(wù)器長(zhǎng)連接處理能力。
功能概述:
每隔10毫秒創(chuàng)建10個(gè)連接,直到目標(biāo)連接數(shù)(比如10k),同時(shí)每個(gè)連接都會(huì)規(guī)律性的向服務(wù)器發(fā)送HEAD請(qǐng)求,以維持HTTP keepavlie。
代碼如下:
- 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()
測(cè)試與分析
硬件:CPU 2.3GHz / 2 cores,RAM 2GB
軟件:CentOS 6.5(kernel 2.6.32), Python 3.3 (pip install asyncio), nginx 1.4.7
參數(shù)設(shè)置:ulimit -n 10240;nginx worker的連接數(shù)改為10240
啟動(dòng)WEB服務(wù)器,只需一個(gè)worker進(jìn)程:
- # ../sbin/nginx
- # ps ax | grep nginx
- 2007 ? Ss 0:00 nginx: master process ../sbin/nginx
- 2008 ? S 0:00 nginx: worker process
啟動(dòng)benchmark工具, 發(fā)起10k個(gè)連接,目標(biāo)URL是nginx的默認(rèn)測(cè)試頁面:
- $ python asyncli.py http://10.211.55.8/ -c 10000
nginx日志統(tǒng)計(jì)平均每秒請(qǐng)求數(shù):
- # tail -1000000 access.log | awk '{ print $4 }' | sort | uniq -c | awk '{ cnt+=1; sum+=$1 } END { printf "avg = %d\n", sum/cnt }'
- avg = 548
top部分輸出:
- 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
總結(jié):
1. Python實(shí)現(xiàn)簡(jiǎn)潔明了。不到80行代碼,只用到標(biāo)準(zhǔn)庫(kù),邏輯直觀,想象下C/C++標(biāo)準(zhǔn)庫(kù)實(shí)現(xiàn)這些功能,頓覺“人生苦短,我用Python”。
2. Python運(yùn)行效率不理想。當(dāng)連接建立后,客戶端和服務(wù)端的數(shù)據(jù)收發(fā)邏輯差不多,看上面top輸出,Python的CPU和RAM占用基本都是nginx的10倍,意味著效率相差100倍(CPU x RAM),側(cè)面說明了Python與C的效率差距。這個(gè)對(duì)比雖然有些極端,畢竟nginx不僅用C且為CPU/RAM占用做了深度優(yōu)化,但相似任務(wù)效率相差兩個(gè)數(shù)量級(jí),除非是BUG,說明架構(gòu)設(shè)計(jì)的出發(fā)點(diǎn)就是不同的,Python優(yōu)先可讀易用而性能次之,nginx就是一個(gè)高度優(yōu)化的WEB服務(wù)器,開發(fā)一個(gè)module都比較麻煩,要復(fù)用它的異步框架,簡(jiǎn)直難上加難。開發(fā)效率與運(yùn)行效率的權(quán)衡,永遠(yuǎn)都存在。
3. 單線程異步IO v.s. 多線程同步IO。上面的例子是單線程異步IO,其實(shí)不寫demo就知道多線程同步IO效率低得多,每個(gè)線程一個(gè)連接?10k個(gè)線程,僅線程棧就占用600+MB(64KB * 10000)內(nèi)存,加上線程上下文切換和GIL,基本就是噩夢(mèng)。
ayncio核心概念
以下是學(xué)習(xí)asyncio時(shí)需要理解的四個(gè)核心概念,更多細(xì)節(jié)請(qǐng)看<參考資料>
1. event loop。單線程實(shí)現(xiàn)異步的關(guān)鍵就在于這個(gè)高層事件循環(huán),它是同步執(zhí)行的。
2. future。異步IO有很多異步任務(wù)構(gòu)成,而每個(gè)異步任務(wù)都由一個(gè)future控制。
3. coroutine。每個(gè)異步任務(wù)具體的執(zhí)行邏輯由一個(gè)coroutine來體現(xiàn)。
4. generator(yield & yield from) 。在asyncio中大量使用,是不可忽視的語法細(xì)節(jié)。
參考資料
1. asyncio – Asynchronous I/O, event loop, coroutines and tasks, https://docs.python.org/3/library/asyncio.html
2. PEP 3156, Asynchronous IO Support Rebooted: the "asyncio” Module, http://legacy.python.org/dev/peps/pep-3156/
3. PEP 380, Syntax for Delegating to a Subgenerator, http://legacy.python.org/dev/peps/pep-0380/
4. PEP 342, Coroutines via Enhanced Generators, http://legacy.python.org/dev/peps/pep-0342/
5. PEP 255, Simple Generators, http://legacy.python.org/dev/peps/pep-0255/
6. asyncio source code, http://hg.python.org/cpython/file/3.4/Lib/asyncio/