当前位置: 首页 > news >正文

httpx 设置速率控制 limit 时需要注意 timeout 包含 pool 中等待时间

假设通过 httpx.Client 设置 limit 速率控制后,同时发起多个请求访问 youtube。并且由于科学原因一直连接不上
假设一共 4 个连接,max_connection=2,timeout=5s。

  • 默认会发生的情况不是前两个连接 tcp 握手 timeout,后两个连接再发起连接 timeout。经过 2 * timeout = 10s 后所有连接失败
  • 默认的配置里,一个请求开始 await 后,由于 limits 限制导致在本地等待的时间也算到总 timeout 里,这就会导致经过 1 * timeout = 5s 后,所有连接全 timeout 了

1. 示例代码

如下示例代码可以证明该问题:

import asyncio
import logging
import os
from asyncio import tasksimport httpxmax_conn = 2
max_keepalive = max_connproject_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "."))
assets_root = os.path.join(project_root, "assets")
cert_path = os.path.join(assets_root, "cert", "cert.pem")
TIMEOUT = 5logging.basicConfig(level=logging.DEBUG)async def __log_content_length__(response: httpx.Response):"""这是一个事件钩子函数,用于在 'response' 事件发生时被调用。"""# 优先尝试从 headers 获取 Content-Lengthcontent_length_header = response.headers.get("Content-Length")if content_length_header is not None:# 如果 header 存在,直接使用body_length = content_length_headerelse:# 如果 header 不存在,计算实际内容的长度...logging.info(f"<-- Received response: {response.status_code} {response.request.method} {response.url} "f"- Length: {body_length} bytes")async def make_req(client: httpx.AsyncClient, url):try:response = await client.get(url)except httpx.TimeoutException as e:logging.error(f"Timeout while making request to {url}: {e}")return Nonereturn responsedef main():limits = httpx.Limits(max_connections=max_conn,max_keepalive_connections=max_keepalive,)httpx_client = httpx.AsyncClient(timeout=TIMEOUT, limits=limits, event_hooks={"response": [__log_content_length__]}, verify=False)tasks = [make_req(httpx_client, f"https://youtube.com") for i in range(10)]async def runner():await asyncio.gather(*tasks)asyncio.run(runner())if __name__ == "__main__":main()

2. 修复方法

timeout 传入一个对象关闭 pool 中 wait 计时

 timeout_config = httpx.Timeout(TIMEOUT, pool=None)
http://www.dtcms.com/a/331834.html

相关文章:

  • Effective C++ 条款40:明智而审慎地使用多重继承
  • 20道Vue框架相关前端面试题及答案
  • Uniapp 中 uni.request 的二次封装
  • stm32f103rct6开发板引脚图
  • 芯伯乐1MHz高频低功耗运放芯片MCP6001/2/4系列,微安级功耗精密信号处理
  • UML函数原型中stereotype的含义,有啥用?
  • 打靶日常-CSRF
  • 中国车企全球化数字转型标杆案例:SAP系统多项目整合升级实践
  • 考研408《计算机组成原理》复习笔记,第五章(2)——CPU指令执行过程
  • Day 11: 预训练语言模型基础 - 理论精华到实战应用的完整指南
  • k8s+isulad 网络问题
  • 【奔跑吧!Linux 内核(第二版)】第7章:系统调用的概念
  • 基本电子元件:电阻器
  • 读书笔记:《我看见的世界》
  • 日志系统(log4cpp)
  • 主进程如何将客户端连接分配到房间进程
  • Android UI(一)登录注册 - Compose
  • 基于Python和Dify的成本对账系统开发
  • OpenCV Canny 边缘检测
  • 软考中级【网络工程师】第6版教材 第3章 局域网 (上)
  • Linux中tty与8250-uart的虐恋(包括双中断发送接收机制)
  • Linux中Samba服务配置与使用指南
  • YouBallin正式上线:用Web3重塑创作者经济
  • 会议通信系统核心流程详解(底稿1)
  • JVM的逃逸分析深入学习
  • 17.2 修改购物车商品
  • RLVR(可验证奖励的强化学习):大模型后训练的客观评估策略
  • 负载因子(Load Factor) :哈希表(Hash Table)中的一个关键性能指标
  • AI大模型+Meta分析:助力发表高水平SCI论文
  • 多任务并发:进程管理的核心奥秘