使用aiohttp/asyncio进行1百万请求 - 字面意思

Pet*_*ung 5 python python-3.x python-asyncio aiohttp python-3.5

我跟进了这个教程:https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html,当我做50 000个请求时,一切正常.但我需要进行1百万个API调用,然后我对此代码有问题:

    url = "http://some_url.com/?id={}"
    tasks = set()

    sem = asyncio.Semaphore(MAX_SIM_CONNS)
    for i in range(1, LAST_ID + 1):
        task = asyncio.ensure_future(bound_fetch(sem, url.format(i)))
        tasks.add(task)

    responses = asyncio.gather(*tasks)
    return await responses
Run Code Online (Sandbox Code Playgroud)

因为Python需要创建100万个任务,它基本上只是滞后然后Killed在终端中打印消息.是否有任何方法可以使用预先制作的(或列表)网址的发生器?谢谢.

Mes*_*ssa 7

一次性安排所有 100 万个任务

这就是您正在谈论的代码。它最多需要 3 GB RAM,因此如果可用内存不足,很容易被操作系统终止。

import asyncio
from aiohttp import ClientSession

MAX_SIM_CONNS = 50
LAST_ID = 10**6

async def fetch(url, session):
    async with session.get(url) as response:
        return await response.read()

async def bound_fetch(sem, url, session):
    async with sem:
        await fetch(url, session)

async def fetch_all():
    url = "http://localhost:8080/?id={}"
    tasks = set()
    async with ClientSession() as session:
        sem = asyncio.Semaphore(MAX_SIM_CONNS)
        for i in range(1, LAST_ID + 1):
            task = asyncio.create_task(bound_fetch(sem, url.format(i), session))
            tasks.add(task)
        return await asyncio.gather(*tasks)

if __name__ == '__main__':
    asyncio.run(fetch_all())
Run Code Online (Sandbox Code Playgroud)

使用队列来简化工作

这是我的建议,如何使用asyncio.Queue将 URL 传递给工作任务。队列根据需要填充,没有预先制作的 URL 列表。

只需要 30 MB RAM :)

import asyncio
from aiohttp import ClientSession

MAX_SIM_CONNS = 50
LAST_ID = 10**6

async def fetch(url, session):
    async with session.get(url) as response:
        return await response.read()

async def fetch_worker(url_queue):
    async with ClientSession() as session:
        while True:
            url = await url_queue.get()
            try:
                if url is None:
                    # all work is done
                    return
                response = await fetch(url, session)
                # ...do something with the response
            finally:
                url_queue.task_done()
                # calling task_done() is necessary for the url_queue.join() to work correctly

async def fetch_all():
    url = "http://localhost:8080/?id={}"
    url_queue = asyncio.Queue(maxsize=100)
    worker_tasks = []
    for i in range(MAX_SIM_CONNS):
        wt = asyncio.create_task(fetch_worker(url_queue))
        worker_tasks.append(wt)
    for i in range(1, LAST_ID + 1):
        await url_queue.put(url.format(i))
    for i in range(MAX_SIM_CONNS):
        # tell the workers that the work is done
        await url_queue.put(None)
    await url_queue.join()
    await asyncio.gather(*worker_tasks)

if __name__ == '__main__':
    asyncio.run(fetch_all())
Run Code Online (Sandbox Code Playgroud)


ami*_*che 2

asyncio 是内存限制的(与任何其他程序一样)。您无法生成内存可以容纳的更多任务。我的猜测是你达到了内存限制。检查 dmesg 以获取更多信息。

100 万 RPS 并不意味着有 1M 个任务。一个任务可以在同一秒内执行多个请求。