Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
黄南光
/
mcp_hive
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 6a7af86b
authored
Sep 14, 2026
by
黄南光
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
优化并发锁问题
1 parent
7fcaa005
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
33 additions
and
18 deletions
src/mcp_hive/services/used_car/api_client.py
src/mcp_hive/services/used_car/api_client.py
View file @
6a7af86
...
...
@@ -7,6 +7,7 @@
from
__future__
import
annotations
import
asyncio
from
collections.abc
import
AsyncIterator
from
contextlib
import
asynccontextmanager
from
typing
import
Any
...
...
@@ -70,21 +71,25 @@ class UsedCarApi:
)
# 工具函数通过这个引用拿到 api 实例;lifespan 负责填充和清空。
# 工具函数通过这个引用拿到 api 实例。
#
# 关键:`lifespan` 不是「进程启动跑一次」,而是 **FastMCP 每建一个 streamable-HTTP
# 会话就跑一次**(server lifespan 随每次 server.run() 进入)。所以 `_api` 是被
# 众多并发会话共享的进程级单例,绝不能让某个会话退出时把它清成 None ——
# 否则另一个还活着的会话下一次 get_api() 就会撞上 None,报「尚未初始化」。
# 用引用计数:第一个会话进来时建池,最后一个会话走了才拆池;只要还有会话在,
# `_api` 就一直非 None。`_lock` 保证「检查-创建/递减-拆除」跨 await 原子。
_api
:
UsedCarApi
|
None
=
None
def
set_api
(
api
:
UsedCarApi
|
None
)
->
None
:
"""设置(或清空,传 None)当前进程内的 UsedCarApi 单例。仅供 lifespan 调用。"""
global
_api
_api
=
api
_refcount
=
0
_lock
=
asyncio
.
Lock
()
def
get_api
()
->
UsedCarApi
:
"""给 tools/ 下的工具函数取当前可用的 UsedCarApi 实例。
服务还没跑完 lifespan 的启动流程就调用工具时主动抛错,
而不是让后续代码在 None 上出现更难懂的报错。
工具调用总是发生在某个活跃会话内部,而只要有会话活跃、引用计数就 >= 1、
`_api` 就非 None,所以正常调用不会走到这里的抛错分支;真抛出来只可能是
装配阶段就没跑过 lifespan(服务未正确挂载)。
"""
if
_api
is
None
:
raise
RuntimeError
(
"UsedCarApi 尚未初始化(服务未正确装配)"
)
...
...
@@ -93,16 +98,26 @@ def get_api() -> UsedCarApi:
@asynccontextmanager
async
def
lifespan
()
->
AsyncIterator
[
UsedCarApi
]:
"""服务生命周期:
建连接池 -> 服务运行 ->
释放。
"""服务生命周期:
第一个会话建连接池 -> 各会话共享 -> 最后一个会话
释放。
以 manifest.py 里 `build_lifespan=api_client.lifespan` 的形式注册给框架。
退出时无论是否异常都会走 finally,避免连接池泄漏。
以 manifest.py 里 `build_lifespan=api_client.lifespan` 的形式注册给框架,
每个 MCP 会话进入/退出各调一次。用引用计数把「进程级单例」的生死和
「并发会话」解耦,避免会话退出时误伤仍在使用该单例的其他会话。
"""
api
=
UsedCarApi
()
await
api
.
start
()
set_api
(
api
)
global
_api
,
_refcount
async
with
_lock
:
if
_api
is
None
:
api
=
UsedCarApi
()
await
api
.
start
()
_api
=
api
_refcount
+=
1
current
=
_api
try
:
yield
api
yield
current
finally
:
set_api
(
None
)
await
api
.
aclose
()
async
with
_lock
:
_refcount
-=
1
if
_refcount
==
0
:
closing
,
_api
=
_api
,
None
if
closing
is
not
None
:
await
closing
.
aclose
()
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment