python network_error ai_generated true

aiohttp.client_exceptions.ClientConnectionError:无法连接到主机 example.com:443 ssl:default [连接被拒绝]

aiohttp.client_exceptions.ClientConnectionError: Cannot connect to host example.com:443 ssl:default [Connection refused]

ID: python/aiohttp-client-connection-pool-exhausted

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-04-05首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.9 active
3.10 active
3.11 active

根因分析

连接池达到限制或服务器因并发请求过多而拒绝连接,通常是因为 ClientSession 的连接器限制过低或连接未释放。

English

The connection pool limit is reached or the server refuses connections due to too many simultaneous requests, often because ClientSession's connector limit is too low or connections are not released.

generic

解决方案

  1. 85% 成功率
    connector = aiohttp.TCPConnector(limit=100, limit_per_host=20)
    async with aiohttp.ClientSession(connector=connector) as session:
        # use session for multiple requests
  2. 90% 成功率
    for attempt in range(3):
        try:
            async with session.get(url) as resp:
                return await resp.text()
        except aiohttp.ClientConnectionError:
            if attempt == 2:
                raise
            await asyncio.sleep(2 ** attempt)

无效尝试

常见但无效的做法:

  1. 50% 失败

    Higher limit can lead to resource exhaustion and doesn't address server-side refusal.

  2. 70% 失败

    Creates many sessions, each with its own pool, causing overhead and still hitting OS limits.