使用 asyncio 并发读写百万级 websocket 长连接,核心在于利用单线程事件循环处理海量 i/o 等待,并通过 aiohttp 或 websockets 库建立非阻塞连接。具体做法是创建一个全局的 asyncio.get_event_loop(),为每个连接分配独立的协程任务,并利用 asyncio.semaphore 限制并发连接数以防止系统资源耗尽。这样做可以在有限的内存和文件描述符限制下,稳定维持大规模连接并实时收发数据。

如何配置 aiohttp 客户端以支持高并发 WebSocket 连接?
配置 aiohttp 客户端支持高并发,关键在于设置合理的 Connector 参数和超时时间。需要使用 TCPConnector 并指定 limit 和 keepalive_timeout,同时启用 force_close=False 以保持连接复用。这样能减少 TCP 握手开销,提升吞吐量。

import asyncio
import aiohttp
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 配置连接器:限制总连接数和每个主机的连接数
connector = aiohttp.TCPConnector(
limit=100, # 总连接池大小
limit_per_host=10, # 单主机最大连接数
keepalive_timeout=30 # 空闲连接保持时间
)
async def connect_ws(url: str, session: aiohttp.ClientSession):
try:
async with session.ws_connect(url) as ws:
logger.info(f"Connected to {url}")
while True:
msg = await ws.receive()
if msg.type == aiohttp.WSMsgType.TEXT:
logger.debug(f"Received: {msg.data}")
elif msg.type == aiohttp.WSMsgType.CLOSED:
break
except Exception as e:
logger.error(f"Connection error: {e}")
async def main():
urls = [f"ws://example.com/ws/{i}" for i in range(10)]
async with aiohttp.ClientSession(connector=connector) as session:
tasks = [connect_ws(url, session) for url in urls]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
如何处理百万级连接中的心跳检测与断线重连?
处理心跳与重连需要在每个连接协程中嵌入定时任务。通过 asyncio.create_task 启动独立的心跳发送协程,并在接收端监控断开信号。一旦检测到连接关闭,立即触发指数退避重连逻辑。这确保了单个连接的故障不会阻塞整个事件循环。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

import asyncio
import random
async def heartbeat(ws, interval: int = 30):
while True:
await asyncio.sleep(interval)
try:
await ws.ping()
except Exception:
break
async def resilient_connect(url: str, max_retries: int = 5):
for attempt in range(max_retries):
try:
async with aiohttp.ClientSession() as session:
async with session.ws_connect(url) as ws:
hb_task = asyncio.create_task(heartbeat(ws))
try:
async for msg in ws:
pass # 处理消息
finally:
hb_task.cancel()
return # 成功连接
except Exception as e:
wait_time = 2 ** attempt + random.random()
logger.warning(f"Retry {attempt+1} after {wait_time}s: {e}")
await asyncio.sleep(wait_time)
logger.error("Max retries reached")
async def main():
await resilient_connect("ws://example.com/ws")
if __name__ == "__main__":
asyncio.run(main())
在内存受限环境下如何优化百万级 WebSocket 连接的状态存储?
在内存受限环境下,优化状态存储的关键是使用轻量级数据结构并定期清理无效连接。避免在每个连接对象中存储大量冗余数据,而是将关键状态(如最后活跃时间、序列号)存储在共享的字典或数据库中。对于百万级连接,建议使用 weakref 或外部缓存(如 Redis)来管理连接元数据,防止内存泄漏。

















