要实现并发的 AWS Lambdas 运行多次,您可以使用 AWS 的服务来实现。
一种解决方案是使用 AWS Step Functions 来调度并发运行的 Lambda 函数。以下是一个示例代码:
import boto3
def lambda_handler(event, context):
# 创建 AWS Step Functions 的客户端
client = boto3.client('stepfunctions')
# 定义并发执行的 Lambda 函数列表
lambdas = ['lambda1', 'lambda2', 'lambda3']
# 创建并发任务列表
tasks = []
for lambda_name in lambdas:
task = {
'Resource': lambda_name,
'TimeoutSeconds': 300,
'End': True
}
tasks.append(task)
# 创建并发任务
response = client.create_state_machine(
name='ConcurrentExecution',
definition={
'Comment': 'A state machine that runs Lambdas concurrently',
'StartAt': 'ConcurrentExecution',
'States': {
'ConcurrentExecution': {
'Type': 'Parallel',
'Branches': tasks,
'ResultPath': '$.results',
'End': True
}
}
},
roleArn='arn:aws:iam::0123456789:role/StepFunctions-Role'
)
return {
'statusCode': 200,
'body': response
}
在上面的代码中,我们首先创建了 AWS Step Functions 的客户端。然后,定义了要并发执行的 Lambda 函数列表,并创建了一个并发任务列表。接下来,使用 create_state_machine
方法创建了一个并发执行的状态机。最后,将创建状态机的响应作为返回结果。
请注意,上述代码只是一个示例,并不包含完整的错误处理和验证逻辑。您可以根据实际需求进行修改和扩展。