首页 > 解决方案 > 使用 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)

标签: python-3.xsemaphorepython-asyncioaiohttp

解决方案


这篇文章已经过时了。

aiohttp默认有 100 个并行连接限制,请参见此处

基本上你不需要信号量(它的功能嵌入到 aiohttp 本身),但应该增加连接池的大小。


推荐阅读