要将死信队列(DLQ)正确附加到通过SNS发布到Lambda的方法,您可以使用AWS CloudFormation来创建相应的资源。下面是一个示例CloudFormation模板,其中包含SNS主题、Lambda函数和DLQ的定义:
Resources:
MyTopic:
Type: AWS::SNS::Topic
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: MyLambdaFunction
Handler: index.handler
Runtime: python3.8
Code:
ZipFile: |
import json
def handler(event, context):
print(event)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
MyDLQ:
Type: AWS::SQS::Queue
MyLambdaEventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref MyLambdaFunction
BatchSize: 10
EventSourceArn: !Ref MyTopic
MaximumRetryAttempts: 2
RetryDelaySeconds: 60
DeadLetterConfig:
TargetArn: !GetAtt MyDLQ.Arn
在上面的示例中,MyTopic是SNS主题,MyLambdaFunction是Lambda函数,MyDLQ是SQS死信队列。MyLambdaEventSourceMapping是用来将SNS主题与Lambda函数关联的Lambda事件源映射。
请注意,DeadLetterConfig属性用于将DLQ附加到事件源映射。TargetArn属性用于指定DLQ的ARN(Amazon 资源名称),这里使用!GetAtt函数来获取MyDLQ资源的ARN。
使用上述CloudFormation模板,您可以通过AWS Management Console、AWS CLI或AWS SDK部署和创建这些资源。