Python 重试机制框架 tenacity 使用

前记

最近在做监控Spring Boot /actuator/health的时候,总是会出现一些莫名其妙的网络超时中断,于是想到了用重试机制来进行重试请求。

下面看看Python的第三方库Tenacity

安装

1
pip install Tenacity

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import requests
from tenacity import retry, stop_after_attempt, wait_fixed

# reraise 表示是否抛出原异常,默认为 False
# stop_after_attempt 表示最大尝试次数
# wait_fixed 表示等待时间
@retry(reraise=True, stop=stop_after_attempt(2), wait=wait_fixed(2))
def main():
print("Start Try " + str(main.retry.statistics["attempt_number"]))
resp = requests.get("https://httpstat.us/200?sleep=5000", timeout=3)
print(resp.status_code)

try:
main()
except Exception as e:
print(str(e))

输出:

1
2
3
Start Try 1
Start Try 2
HTTPSConnectionPool(host='httpstat.us', port=443): Read timed out. (read timeout=3)

上面示例中,设定超时为3s请求却sleep=5000此请求必然会超时

tenacity只要遇见raise就会触发重试,上面代码中requests底层已经raise,所以即使main函数中没有raise依然会重试

参考文档