rabbitmq Django Celery停留在待定状态

xqnpmsa8  于 2022-12-23  发布在  RabbitMQ
关注(0)|答案(1)|浏览(196)
    • bounty将在6天后过期**。回答此问题可获得+50声望奖励。MC2020希望引起更多人关注此问题。

我试图在我的django应用中使用celery 来加速函数的处理时间,但我无法让它正常工作。我使用的是RabbitMQ。
my tasks.py

from celery import Celery
from celery import shared_task,current_task
from myapp.celery import app

@app.task
def add(x,y):
    
    for i in range(25000000):
        a = x+y
    
    return x+y

我的python代码

def test_multi_func():
    x = 5
    y = 10
    i = 15
    print(f"start = {time.perf_counter()}")
    while i > 0:
        g = add.delay(x,y)
        result = add.AsyncResult(g)
        i -= 1
    print(result.backend)
    print(result.status)
    print(f"end = {time.perf_counter()}")
    print(f"g = {g.get()}")
    print(f"x = {x} ; y = {y}")

my settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_select2',
    'chartjs',
    'django_material_icons',
    'material',
    'django_celery_results',
    'celery_progress',
    'django_apscheduler'
]

BROKER_URL = 'django://'
result_backend = 'django-db'
CELERY_RESULT_BACKEND = 'django-db'
result_persistent = True
task_result_expires = None
send_events = True
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_BROKER_URL = 'amqp://localhost'
CELERY_CACHE_BACKEND = 'django-cache'
CELERY_IGNORE_RESULT = False

my celery.py

import os

from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

app = Celery('myapp',
             backend='amqp://guest@localhost:15672/',
             broker='amqp://guest@localhost:15672/',
             include=['myapp.tasks'])

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

我做错了什么?我很难理解这一点。它触发了test_multi_func(),然后在RabbitMQ中停留在挂起状态,什么也没发生。如果有人能帮助我了解我需要做什么不同的事情,我将非常感激。我已经尝试了许多不同的迭代,我可以在网上找到不同的代码,似乎没有工作。

dffbzjpn

dffbzjpn1#

你的celepie配置有很多冲突,我想知道你是如何运行worker的。
1.在你的settings.py,中,你混合了传统和新的Celery配置风格,对于Celery 4和更高版本,小写的配置设置是首选的:https://docs.celeryq.dev/en/stable/userguide/configuration.html#new-lowercase-settings
1.您已经配置了两次代理URL(amqp://guest@localhost:15672/amqp://localhost),并且配置了两个不同的结果后端。
1.您已经向Celery示例传递了三次配置,并且设置相互影响。具体来说,当我们将设置直接传递给Celery类时,* 应该 * 如下所示:

app = Celery('myapp',
             backend_url='amqp://guest@localhost:15672/',
             broker_backend='amqp://guest@localhost:15672/',
             include=['myapp.tasks'])

如果愿意,您还可以创建Celery示例并分两步配置它:

app = Celery('myapp')
app.conf.update(broker_url='amqp://guest@localhost:15672/',
                result_backend='amqp://guest@localhost:15672/')

相关问题