perf: 优化 celery 任务中的数据库连接问题

perf: add comment
pull/7498/head
ibuler 2022-01-17 11:07:27 +08:00 committed by Jiangjie.Bai
parent e1de210585
commit 451e61bb61
2 changed files with 13 additions and 1 deletions

View File

@ -44,6 +44,7 @@ def get_objects(model, pks):
return objs
# 复制 django.db.close_old_connections, 因为它没有导出ide 提示有问题
def close_old_connections():
for conn in connections.all():
conn.close_if_unusable_or_obsolete()

View File

@ -1,6 +1,8 @@
from django.utils import translation
from django.core.cache import cache
from celery.signals import task_prerun, before_task_publish
from celery.signals import task_prerun, task_postrun, before_task_publish
from common.db.utils import close_old_connections
TASK_LANG_CACHE_KEY = 'TASK_LANG_{}'
@ -17,7 +19,16 @@ def before_task_publish(headers=None, **kwargs):
@task_prerun.connect()
def on_celery_task_pre_run(task_id='', **kwargs):
# 关闭之前的数据库连接
close_old_connections()
# 保存 Lang context
key = TASK_LANG_CACHE_KEY.format(task_id)
task_lang = cache.get(key)
if task_lang:
translation.activate(task_lang)
@task_postrun.connect()
def on_celery_task_post_run(**kwargs):
close_old_connections()