from gevent import monkey; monkey.patch_all()
import asyncio
import time
import requests
import aiohttp
import sys
import threading
import gevent
import queue
'''
基于协程的各种并发请求示例
在运行程序时 传入指定的命令行参数来开启执行的并发方式
ttp://127.0.0.1:8000/test/ 是本地实现的一个耗时两秒左右的接口
需要安装相应的包:pip install aiohttp gevent
'''
async def fetch(url, q):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
res = await response.text()
q.put(res)
return res
async def run_task(num, q):
tasks = []
for i in range(num):
tasks.append(asyncio.create_task(fetch('http://127.0.0.1:8000/test/',q)))
await asyncio.wait(tasks)
async def run_gather(num, q):
tasks = []
for i in range(num):
tasks.append(asyncio.create_task(fetch('http://127.0.0.1:8000/test/',q)))
await asyncio.gather(*tasks)
async def run_loop_task(num, q, loop):
tasks = []
for i in range(num):
task = loop.create_task(fetch('http://127.0.0.1:8000/test/', q))
tasks.append(task)
await asyncio.gather(*tasks)
async def bound_fetch(sem, q):
async with sem:
await fetch('http://127.0.0.1:8000/test/', q)
if __name__ == '__main__':
q = queue.Queue()
start_time = time.time()
if len(sys.argv) > 1 and sys.argv[1] == '1':
asyncio.run(run_task(2, q))
if len(sys.argv) > 1 and sys.argv[1] == '2':
asyncio.run(run_gather(2, q))
elif len(sys.argv) > 1 and sys.argv[1] == '3':
loop = asyncio.get_event_loop()
tasks = []
for i in range(2):
task = loop.create_task(fetch('http://127.0.0.1:8000/test/', q))
tasks.append(task)
loop.run_until_complete(asyncio.wait(tasks))
elif len(sys.argv) > 1 and sys.argv[1] == '4':
loop = asyncio.get_event_loop()
tasks = []
for i in range(2):
task = loop.create_task(fetch('http://127.0.0.1:8000/test/', q))
tasks.append(task)
loop.run_until_complete(asyncio.gather(*tasks))
elif len(sys.argv) > 1 and sys.argv[1] == '5':
loop = asyncio.get_event_loop()
loop.run_until_complete(fetch('http://127.0.0.1:8000/test/', q))
elif len(sys.argv) > 1 and sys.argv[1] == '6':
loop = asyncio.get_event_loop()
loop.run_until_complete(run_loop_task(2, q, loop))
elif len(sys.argv) > 1 and sys.argv[1] == '7':
loop = asyncio.get_event_loop()
tasks = []
sem = asyncio.Semaphore(1000)
for i in range(2):
task = loop.create_task(bound_fetch(sem, q))
tasks.append(task)
loop.run_until_complete(asyncio.gather(*tasks))
while q.qsize() != 0:
print(q.get())
print('耗时:', time.time() - start_time)