在 API 网关中使用节流技术可确保对后端服务的请求流量进行限制,从而防止后端服务过载而崩溃。示例代码如下:
import time import decimal import boto3 from boto3.dynamodb.conditions import Key, Attr
TABLE_NAME = 'MyTable'
ALLOWED_RATE = 10
ddb_client = boto3.resource('dynamodb') ddb_table = ddb_client.Table(TABLE_NAME)
def handler(event, context): # 客户端IP ip_address = event['requestContext']['identity']['sourceIp']
# 时间戳
timestamp = decimal.Decimal(time.time())
# 检查该IP地址最近一段时间内的请求次数
ip_address_requests = ddb_table.query(
KeyConditionExpression=Key('IPAddress').eq(ip_address) & Key('Timestamp').gt(timestamp - decimal.Decimal(60))
)
# 如果请求次数超过了允许的速率,则抛出错误
if ip_address_requests['Count'] > ALLOWED_RATE:
raise Exception('Rate limit exceeded')
# 否则允许请求通过
return {
'statusCode': 200,
'body': 'Hello from API Gateway!'
}