如何覆盖芹菜任务的后端

时间:2015-05-07 13:16:33

标签: python celery celery-task

我们使用Redis作为结果后端。但是对于一项任务,我们想要覆盖它以使用RabbitMQ。

Task.backend的文档说:

  

结果存储后端用于此任务。默认为   CELERY_RESULT_BACKEND设置

所以我假设我们可以将Task.backend设置为CELERY_RESULT_BACKEND接受的相同格式的字符串。

所以我试试这个:

celeryconfig.py

CELERY_RESULT_BACKEND = "redis://redis-host:7777"

tasks.py

@app.task(backend='amqp://guest@localhost/tasks-stg')
def my_task(params):
    ...

然而,工人失败了:

[2015-05-07 13:33:49,264: ERROR/Worker-1] Process Worker-1
Traceback (most recent call last):
  File "/project/python2.7_x64/lib/python2.7/site-packages/billiard/process.py", line 292, in _bootstrap
    self.run()
  File "/project/python2.7_x64/lib/python2.7/site-packages/billiard/pool.py", line 286, in run
    self.after_fork()
  File "/project/python2.7_x64/lib/python2.7/site-packages/billiard/pool.py", line 389, in after_fork
    self.initializer(*self.initargs)
  File "/project/python2.7_x64/lib/python2.7/site-packages/celery/concurrency/prefork.py", line 81, in process_initializer
    app=app)
  File "/project/python2.7_x64/lib/python2.7/site-packages/celery/app/trace.py", line 178, in build_tracer
    store_result = backend.store_result
AttributeError: 'str' object has no attribute 'store_result'

2 个答案:

答案 0 :(得分:2)

文档不正确。 Task.backend实际上是来自celery.backends的后端类的实例。在这种情况下,要覆盖任务类,我必须这样做:

from celery.backends.amqp import AMQPBackend

@app.task(backend=AMQPBackend(app, url='amqp://guest@localhost/tasks-stg'))
def my_task(params):
    ...

然而,工作人员继续使用默认课程并且似乎没有提供覆盖此方法的方法。

答案 1 :(得分:0)

扩展并更新原始接受的答案,遇到类似问题的人可能会对 List of Options available in Celery task decorator 感兴趣。请参阅Task.backend部分:

<块引用>

用于此任务的结果存储后端。 celery.backends 中后端类之一的实例。默认为 app.backend

此外,从 5.0 版开始,AMQP result backend has been removed 可以改为使用 celery.backends.rpc.RPCBackend

例如:

from celery.backends.rpc import RPCBackend as CeleryRpcBackend
_rpc_backend = CeleryRpcBackend(app=your_celery_app, \
        exchange=RPC_REPLY_EXCHANGE_DEFAULT_NAME, \
        exchange_type=RPC_EXCHANGE_DEFAULT_TYPE )

@your_celery_app.task(backend=_rpc_backend, ... OTHER_ARGS ... )
def your_task_function(**kwargs):
    DO_SOMETHING ...