python-3.x - 使用 aiohttp 的响应时间会随着时间的推移而增加
问题描述
我有一个 API“localhost/service”,在串行请求时平均需要 2 秒才能返回,而当我设置 10 个线程并行请求它时,大约需要 8 秒。我想使用 asyncio 复制这些数字,没有线程。我决定这样做的方法是遵循本文的代码并将信号量设置为 10。对于前 20 个左右的请求,我得到的响应时间为 8 秒,但之后响应时间开始显着增加。我一直在使用邮递员请求服务器,并且它始终返回 8 秒的响应时间,而这个使用 asyncio 的脚本报告每个请求的时间超过一分钟。我在这里做错了什么?
import time
import asyncio
from aiohttp import ClientSession
async def fetch(url, session):
start = time.monotonic()
async with session.get(url) as response:
end = round(time.monotonic() - start, 4)
print("response time: {}".format(end))
return await response.read()
async def bound_fetch(sem, url, session):
# Getter function with semaphore.
async with sem:
await fetch(url, session)
async def run(r):
url = 'http://localhost:8080/service'
tasks = []
# create instance of Semaphore
sem = asyncio.Semaphore(10)
# Create client session that will ensure we dont open new connection
# per each request.
async with ClientSession() as session:
for i in range(r):
# pass Semaphore and session to every GET request
task = asyncio.ensure_future(bound_fetch(sem, url.format(i), session))
tasks.append(task)
responses = asyncio.gather(*tasks)
await responses
number = 10000
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(number))
loop.run_until_complete(future)
解决方案
推荐阅读
- javascript - 解决 eslint(node/no-unsupported-features/es-syntax) - 如何在 ESLint 中支持 JavaScript 模块?
- java - java.sql.SQLException:用户'root'@'localhost'的访问被拒绝(使用密码:是)
- android - 停止 asynctask 被调用两次
- python - 在虚拟专用服务器中运行 Flask Web 应用程序而不显示代码
- angular - 防止刷新反应形式Angular 2
- python - 从列表中提取时间值并添加到新列表或数组中
- django - 当过滤字符串为空时,如何停止 Graphql + Django-Filters 返回所有对象?
- javascript - 单击按钮时如何使元素出现和动画
- c# - 当正则表达式在 C# 数据注释 asp.net core 2 中失败时出现 500 内部服务器错误
- ssis - 使用三个 SSIS 项目重建解决方案时出现 System.OutOfMemoryException