40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
"""Neo4j 会话:全局单例 AsyncDriver(内部自带连接池与事务重试)。"""
|
||
from neo4j import AsyncGraphDatabase
|
||
from config.settings import settings
|
||
|
||
_driver = None
|
||
|
||
|
||
def client():
|
||
global _driver
|
||
if _driver is None:
|
||
_driver = AsyncGraphDatabase.driver(
|
||
settings.neo4j.uri,
|
||
auth=(settings.neo4j.user, settings.neo4j.password),
|
||
max_connection_pool_size=settings.neo4j.max_connection_pool_size,
|
||
connection_acquisition_timeout=settings.neo4j.connection_acquisition_timeout,
|
||
connection_timeout=settings.neo4j.connection_timeout,
|
||
max_transaction_retry_time=settings.neo4j.max_transaction_retry_time,
|
||
)
|
||
return _driver
|
||
|
||
|
||
async def init_db() -> None:
|
||
client() # 构造为懒连接,仅建出 driver 单例
|
||
|
||
|
||
async def get_session():
|
||
"""每次操作取一个轻量 pool 内 session;execute_read/write 自带事务重试。"""
|
||
async with client().session() as s:
|
||
yield s
|
||
|
||
|
||
async def dispose() -> None:
|
||
global _driver
|
||
if _driver is not None:
|
||
await _driver.close()
|
||
_driver = None
|
||
|
||
|
||
async def check_health() -> None:
|
||
await client().verify_connectivity() |