并发请求被挂起。下面是我用来测试并发请求的示例代码。
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,那么所有100个请求将在5秒内完成,而不会挂起。
我不知道我在这里做什么。任何帮助都将受到高度的感谢。
发布于 2019-05-03 04:27:34
我可以使用: 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)) https://stackoverflow.com/questions/55697901
复制相似问题