异常重试

retrying是一个Python的重试包,可以用来自动重试一些可能运行失败的程序段。retrying提供一个装饰器函数retry,被装饰的函数就会在运行失败的条件下重新执行,默认只要一直报错就会不断重试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random
from retrying import retry

@retry
def do_something():
num = random.randint(0, 20)
if num > 1:
print(num)
raise Exception('出现异常!', RuntimeError)
else:
print(num)

if __name__ == '__main__':
do_something()

retry还可以接受一些参数:
stop_max_attempt_number:用来设定最大的尝试次数,超过该次数就停止重试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random
from retrying import retry

@retry(stop_max_attempt_number=2)
def do_something():
num = random.randint(0, 20)
if num > 1:
print(num)
raise Exception('出现异常!', RuntimeError)
else:
print(num)

if __name__ == '__main__':
do_something()

stop_max_delay:比如设置成2000,那么从被装饰的函数开始执行的时间点开始,到函数成功运行结束或者失败报错中止的时间点,只要这段时间超过2秒,函数就不会再执行了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random
from retrying import retry

@retry(stop_max_delay=2000)
def do_something():
num = random.randint(0, 20)
if num > -1:
print(num)
raise Exception('出现异常!', RuntimeError)
else:
print(num)

if __name__ == '__main__':
do_something()

wait_fixed:设置在两次retrying之间的停留时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random
from retrying import retry

@retry(stop_max_delay=10000, wait_fixed=1000)
def do_something():
num = random.randint(0, 20)
if num > -1:
print(num)
raise Exception('出现异常!', RuntimeError)
else:
print(num)

if __name__ == '__main__':
do_something()

wait_random_min和wait_random_max:用随机的方式产生两次retrying之间的停留时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random
from retrying import retry

@retry(stop_max_delay=10000, wait_random_min=1000, wait_random_max=2000)
def do_something():
num = random.randint(0, 20)
if num > -1:
print(num)
raise Exception('出现异常!', RuntimeError)
else:
print(num)

if __name__ == '__main__':
do_something()

wait_exponential_multiplier和wait_exponential_max:以指数的形式产生两次retrying之间的停留时间,产生的值为2previous_attempt_number * wait_exponential_multiplier,previous_attempt_number是前面已经retrying过的次数,如果产生的这个值超过了wait_exponential_max的大小,那么之后两个retrying之间的停留值都为wait_exponential_max。这个设计迎合了exponential backoff算法,可以减轻阻塞的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random
from retrying import retry

@retry(stop_max_delay=10000, wait_exponential_multiplier=1, wait_exponential_max=3000)
def do_something():
num = random.randint(0, 20)
if num > -1:
print(num)
raise Exception('出现异常!', RuntimeError)
else:
print(num)

if __name__ == '__main__':
do_something()

retry_on_exception:指定要在出现哪些异常的时候再去retrying。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import random
from retrying import retry

def retry_if_io_error(exception):
return isinstance(exception, IOError)

@retry(retry_on_exception=retry_if_io_error)
def do_something():
num = random.randint(0, 20)
if num >= 0 and num < 10:
print(num)
raise Exception('出现异常!', IOError)
else:
print(num)
raise Exception('出现异常!', OSError)

if __name__ == '__main__':
do_something()