mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
fix: 修复 ManageApiClient 关闭期间的连接池创建竞态
This commit is contained in:
parent
82e3c1874f
commit
32cba36237
1 changed files with 30 additions and 26 deletions
|
|
@ -60,14 +60,16 @@ class ManageApiClient:
|
|||
"""确保异步客户端已创建(为每个事件循环创建独立的客户端)"""
|
||||
import asyncio
|
||||
|
||||
if cls._closed:
|
||||
raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端")
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
loop_id = id(loop)
|
||||
|
||||
# 为每个事件循环创建独立的客户端
|
||||
# 检查关闭状态与创建连接池必须是同一个临界区,避免 safe_close()
|
||||
# 清空连接池后又有请求将新客户端写回。
|
||||
with cls._instance_lock:
|
||||
if cls._closed:
|
||||
raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端")
|
||||
|
||||
if loop_id not in cls._async_clients:
|
||||
# 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
|
||||
limits = httpx.Limits(
|
||||
|
|
@ -176,13 +178,15 @@ class ManageApiClient:
|
|||
|
||||
with cls._instance_lock:
|
||||
cls._closed = True
|
||||
for client in list(cls._async_clients.values()):
|
||||
clients = list(cls._async_clients.values())
|
||||
cls._async_clients.clear()
|
||||
cls._instance = None
|
||||
|
||||
for client in clients:
|
||||
try:
|
||||
asyncio.run(client.aclose())
|
||||
except Exception:
|
||||
pass
|
||||
cls._async_clients.clear()
|
||||
cls._instance = None
|
||||
|
||||
|
||||
def api_guard(error_msg: str = None, raise_when_closed: bool = False):
|
||||
|
|
|
|||
Loading…
Reference in a new issue