AWS Lambda在受到频繁请求时,会触发频率限制,导致函数调用失败。为了解决这个问题,可以在Lambda函数内部实现一个重试机制,从而降低函数调用失败率。
以下是一个示例代码,其中使用了Boto3的retry装饰器来实现重试机制:
import boto3
from botocore.exceptions import ClientError
from functools import wraps
def retry_on_throttling(retry_limit=3):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
retry_count = 0
while True:
try:
return func(*args, **kwargs)
except ClientError as e:
if e.response['Error']['Code'] == 'TooManyRequestsException' and retry_count < retry_limit:
print('Lambda is being throttled. Retrying ...')
retry_count += 1
else:
raise e
return wrapper
return decorator
@retry_on_throttling()
def lambda_handler(event, context):
# Your code here
在上面的示例中,@retry_on_throttling()装饰器装饰的函数将会被重试3次,直到函数成功返回或者达到重试次数上限。如果Lambda函数受到频率限制,将会在控制台输出“Lambda is being throttled. Retrying ...”这个信息。
此外,为了减少频率限制的发生,还可以在代码中加入一些优化策略,例如增加缓存、分批请求等。