Files
Mutual_Fund/config/database/neo4j.py
2026-09-08 19:17:35 +08:00

40 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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()