AWS Lambda和ALB之间具有1MB有效载荷限制。这意味着当您使用ALB触发Lambda函数时,有效载荷的大小不能超过1MB。这是因为ALB不能将超过1MB的有效负载发送到Lambda,因此必须在使用ALB作为触发器时遵守此限制。
为了解决此问题,您可以将有效负载拆分为小块,处理每个块并将它们组合起来。您可以使用以下示例代码来解决此问题:
import json import boto3
def lambda_handler(event, context): # Get the S3 and ALB objects from the event s3 = boto3.client('s3') alb = boto3.client('elbv2')
# Get the object key and bucket from the S3 event
bucket_name = event['Records'][0]['s3']['bucket']['name']
object_key = event['Records'][0]['s3']['object']['key']
# Get the object size
object_info = s3.head_object(Bucket=bucket_name, Key=object_key)
# Get the object data in chunks
chunk_size = 1024 * 1024 # 1MB
start_byte = 0
end_byte = chunk_size
chunks = []
while start_byte < object_info['ContentLength']:
obj = s3.get_object(Bucket=bucket_name, Key=object_key, Range=f'bytes={start_byte}-{end_byte - 1}')
chunks.append(obj['Body'].read())
start_byte = end_byte
end_byte += chunk_size
# Concatenate the chunks and return the data
data = b''.join(chunks)
return {
'statusCode': 200,
'body': data.decode('utf-8')
}
在这个示例中,我们的Lambda函数触发ALB并从S3下载对象。我们使用S3 API来获取对象的大小并将其分割成1MB的块。我们使用boto3 APIs从S3中获取数据块,然后使用b''join()将它们组合起来。最后,我们以文本格式返回数据。
注意:当使用ALB作为Lambda函数触发器时,请注意有效负载的大小限制。如果超过1MB,我们建议您使用其他Lambda触发器,例如API网关。