aiohttp-并发请求被挂起

时间:2019-04-15 22:12:06

标签: python-3.7 aiohttp

并发请求被挂起。这是我用来测试并发请求的示例代码。

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        print(await response.text())

async def main(n):
    url = "https://httpstat.us/200"
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.create_task(fetch(session, url)) for _ in range n]
        await asyncio.gather(*tasks)

asyncio.run(main(10))

当我发出10个并发请求时,同时发出前4-5个请求,然后将其挂起10秒钟以上,然后开始运行2-3个并发请求后再次挂起的其余任务。如果我发出100个并发请求,它将发出25-30个并发请求并被挂起,然后发出5-6个请求并再次被挂起,直到所有任务完成为止。

使用aiohttp向https://httpstat.us/200发送100个请求需要花费两分钟的时间。

如果我不使用持久性ClientSession并为每个请求创建新的ClientSession,那么所有数百个请求将在5秒内完成而不会挂起。

我不确定我在这里做什么。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我能够使用以下代码运行此代码: python 3.7,asyncio 3.4.3,aiohttp 3.5.4

import aiohttp 
import asyncio 

async def fetch(session, url): 
    async with session.get(url) as response: 
        print(await response.text()) 

async def main(n): 
    url = "https://httpstat.us/200" 
    async with aiohttp.ClientSession() as session: 
        tasks = [asyncio.create_task(fetch(session, url)) for _ in range (0,n)] 
        await asyncio.gather(*tasks) 

asyncio.run(main(10))  
相关问题