0

我有大约 130 个异步 GET 请求正在 python 中使用 httpx 和 asyncio 通过我自己在 AWS 上创建的代理发送。

在 python 脚本中,我打印了每个请求发送之前的时间,可以看到它们都在不到 70 毫秒内发送。但是,我通过立即获取当前时间来计时请求的持续时间,有些请求最多需要 30 秒!这段时间的分布似乎相当水平,所以我每秒收到大约 3-5 个请求,持续 30 秒。

我使用tcpdump和wireshark查看返回的数据包,似乎所有应用程序数据都在4秒内返回(包括tcp握手)所以我不明白python延迟的原因。

tcp 拆卸发生在 35 秒后,所以这可能是延迟的原因?在 httpx.get() 被解除阻塞并且可以读取请求之前,httpx 是否等待连接关闭(FIN 和 ACK)?

我可以尝试什么来加快速度?

这是我的代码的简化版本:

import asyncio
import datetime

import httpx

from utils import store_data, get_proxy_addr


CLIENT = None

async def get_and_store_thing_data(thing):
    t0 = datetime.now()
    res = await CLIENT.get('https://www.placetogetdata.com', params={'thing': thing})
    t1 = datetime.now()
    # It's this line that shows the time is anywhere from 0-30 seconds for the
    # request to return
    print(f'time taken: {t1-t0}')
    data = res.json()
    store_data(data)
    return data


def get_tasks(things):
    tasks = []
    for thing in things:
        tasks = get_and_store_thing_data(thing)
        tasks.append(tasks)

    return tasks


async def run_tasks(tasks):
    global CLIENT
    CLIENT = httpx.AsyncClient(proxies={'https://': proxy_addr})
    try:
        await asyncio.wait(tasks)
    finally:
        await CLIENT.aclose()


def run():
    proxy_addr = get_proxy_addr()
    tasks = get_tasks
    asyncio.run(run_tasks(tasks, proxy_addr))
4

0 回答 0