在AWS Lambdas中,可以使用速率限制来限制函数的调用速率。以下是一种解决方法的示例代码:
import boto3
def lambda_handler(event, context):
# Your code here
return {
'statusCode': 200,
'body': 'Hello, world!'
}
def create_rate_limiter(limit_per_minute):
client = boto3.client('waf-regional')
response = client.create_rate_based_rule(
Name='MyRateLimiter',
MetricName='MyRateLimiter',
RateKey='IP',
RateLimit={
'MaxRateLimit': limit_per_minute,
'BurstLimit': limit_per_minute
}
)
rate_limiter_arn = response['Rule']['MetricName']
return rate_limiter_arn
def associate_rate_limiter_with_lambda(rate_limiter_arn, function_name):
client = boto3.client('waf-regional')
response = client.update_rule_group(
RuleGroupName='AWSLambdaRateLimit',
Updates=[
{
'Action': 'INSERT',
'ActivatedRule': {
'Priority': 1,
'RuleId': rate_limiter_arn,
'Action': {
'Type': 'COUNT'
}
}
}
]
)
return response
rate_limiter_arn = create_rate_limiter(100) # 设置每分钟最大限制 100
response = associate_rate_limiter_with_lambda(rate_limiter_arn, 'MyLambdaFunction') # 替换为你的Lambda函数名称
以上代码示例了如何在AWS Lambdas中创建和使用速率限制器。你可以根据自己的需求,调整限制器的速率和其他参数。