编程语言
首页 > 编程语言> > Python – 从另一个队列重试失败的Celery任务

Python – 从另一个队列重试失败的Celery任务

作者:互联网

我正在向Celery的网络服务发布数据.有时,由于互联网关闭,数据不会发布到Web服务,并且任务会在发布之前无限次重试.重新执行任务是不必要的,因为网络已关闭,因此不需要再次重新尝试.

我想到了一个更好的解决方案,即如果任务失败三次(重试3次),则转移到另一个队列.此队列包含所有失败任务的列表.
现在,当互联网启动并且数据通过网络发布时,即任务已从正常队列完成,然后它开始处理任务失败的队列中的任务.
这不会浪费CPU内存一次又一次地重试任务.

这是我的代码: – 截至目前,我只是再次重试这项任务,但我怀疑这是否是正确的做法.

@shared_task(default_retry_delay = 1 * 60, max_retries = 10)
def post_data_to_web_service(data,url):

    try : 
        client = SoapClient(
                            location = url,
                            action = 'http://tempuri.org/IService_1_0/',
                            namespace = "http://tempuri.org/", 
                            soap_ns='soap', ns = False
                            )

        response= client.UpdateShipment(
                                        Weight = Decimal(data['Weight']), 
                                        Length = Decimal(data['Length']), 
                                        Height = Decimal(data['Height']), 
                                        Width =  Decimal(data['Width']) , 
                                        )

    except Exception, exc:
        raise post_data_to_web_service.retry(exc=exc) 

如何同时维护2个队列并尝试从两个队列执行任务.

Settings.py

BROKER_URL = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

解决方法:

默认情况下,celery将所有任务添加到名为celery的队列中.所以你可以在这里运行你的任务,当一个异常发生时,它重试,一旦达到最大重试次数,你可以将它们转移到一个新的队列说foo

from celery.exceptions import MaxRetriesExceededError

@shared_task(default_retry_delay = 1 * 60, max_retries = 10)
def post_data_to_web_service(data,url):
    try:
        #do something with given args

 except MaxRetriesExceededError:
        post_data_to_web_service([data, url], queue='foo')

 except Exception, exc:
        raise post_data_to_web_service.retry(exc=exc) 

启动工作人员时,此任务将尝试对给定数据执行某些操作.如果失败,它将以60秒的时间重试10次.然后,当遇到MaxRetriesExceededError时,它会将相同的任务发布到新队列foo.

要使用这些任务,您必须启动一个新工作者

celery worker -l info -A my_app -Q foo

或者,如果您启动它,也可以从默认工作程序中使用此任务

 celery worker -l info -A my_app -Q celery,foo

标签:python,celery,django-celery
来源: https://codeday.me/bug/20191007/1866457.html