python使用rabbitmq worker异常处理
程序员文章站
2022-07-15 12:59:09
...
在使用rabbitmq时,如果服务端重启或者异常,worker就会抛出异常而导致挂掉,这里写了一个简单的重试机制
def auto_restart(max_retry=None, sleep_time=5):
def wrapper(func):
def _inner(*args, **kwargs):
retry = 0
condition = retry < max_retry if max_retry else True
while condition:
retry += 1
try:
func(*args, **kwargs)
except Exception as e:
traceback.print_exc()
print(f'service down. {retry} time retry. restarting in {sleep_time}s')
time.sleep(sleep_time)
print('service closed.')
return _inner
return wrapper
max_retry 是重试的最大次数,sleep_time为异常后间隔多久重试 单位为秒;
使用方式也是非常滴银杏,哈哈哈哈
@auto_restart(max_retry=100)
def handle(self, *args, **options):
mq = MessageQueue(RABBIT_HOST, RABBIT_USER, RABBIT_PASS)
mq.init()
mq.work('queue_name', mq.push_msg)