mirror of
https://github.com/jumpserver/jumpserver.git
synced 2025-09-16 07:18:22 +00:00
perf: playbook task db save if conn timeout
This commit is contained in:
@@ -50,13 +50,14 @@ def get_objects(model, pks):
|
||||
|
||||
|
||||
# 复制 django.db.close_old_connections, 因为它没有导出,ide 提示有问题
|
||||
def close_old_connections():
|
||||
for conn in connections.all():
|
||||
def close_old_connections(**kwargs):
|
||||
for conn in connections.all(initialized_only=True):
|
||||
conn.close_if_unusable_or_obsolete()
|
||||
|
||||
|
||||
# 这个要是在 Django 请求周期外使用的,不能影响 Django 的事务管理, 在 api 中使用会影响 api 事务
|
||||
@contextmanager
|
||||
def safe_db_connection(auto_close=True):
|
||||
def safe_db_connection():
|
||||
close_old_connections()
|
||||
yield
|
||||
close_old_connections()
|
||||
@@ -64,19 +65,25 @@ def safe_db_connection(auto_close=True):
|
||||
|
||||
@contextmanager
|
||||
def safe_atomic_db_connection(auto_close=False):
|
||||
in_atomic_block = connection.in_atomic_block # 当前是否处于事务中
|
||||
autocommit = transaction.get_autocommit() # 是否启用了自动提交
|
||||
created = False
|
||||
"""
|
||||
通用数据库连接管理器(线程安全、事务感知):
|
||||
- 在连接不可用时主动重建连接
|
||||
- 在非事务环境下自动关闭连接(可选)
|
||||
- 不影响 Django 请求/事务周期
|
||||
"""
|
||||
in_atomic = connection.in_atomic_block # 当前是否在事务中
|
||||
autocommit = transaction.get_autocommit()
|
||||
recreated = False
|
||||
|
||||
try:
|
||||
if not connection.is_usable():
|
||||
connection.close()
|
||||
connection.connect()
|
||||
created = True
|
||||
recreated = True
|
||||
yield
|
||||
finally:
|
||||
# 如果不是事务中(API 请求中可能需要提交事务),则关闭连接
|
||||
if auto_close or (created and not in_atomic_block and autocommit):
|
||||
# 只在非事务、autocommit 模式下,才考虑主动清理连接
|
||||
if auto_close or (recreated and not in_atomic and autocommit):
|
||||
close_old_connections()
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user