【发布时间】:2021-12-20 01:37:34
【问题描述】:
如果我在使用 Gunicorn 或 uWsgi 时将 celery 与 Django 一起使用(通过调用 .delay()),它会导致它冻结并最终超时。我猜它在尝试向代理发送任务时会卡住。这发生在开发者服务器和生产服务器上,两者都运行 Ubuntu 20.04。
使用内置的开发者服务器 python3 manage.py 运行服务器 工作没有任何问题。
删除 .delay() 也会使其自动工作。
示例任务:
@shared_task
def SayHello():
print('Hello!')
settings.py 中的 Celery 配置:
CELERY_BROKER_URL = 'redis://:password@ip:6379'
CELERY_RESULT_BACKEND = 'redis://:password@ip:6379'
CELERY_ACCEPT_CONTENt = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER ='json'
初始化.py:
from __future__ import absolute_import, unicode_literals
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
__all__ = ('celery_app',)
celery.py(在带有 settings.py 的项目文件夹中):
import os
from celery import Celery
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings')
app = Celery('djangoProject')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django apps.
app.autodiscover_tasks()
celery = Celery(__name__)
celery.config_from_object(__name__)
@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')
【问题讨论】:
标签: django django-rest-framework redis celery gunicorn