问题描述: 当使用AWS Lambda SQS触发器时,如果队列被删除并重新创建,Lambda触发器将不会再次触发。
解决方法: 要解决这个问题,可以使用CloudFormation模板和AWS Lambda函数来重新创建队列并更新触发器。
以下是一个使用AWS CloudFormation模板和AWS Lambda函数的示例:
Resources:
MyQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: MyQueue
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: MyLambdaFunction
Runtime: python3.8
Handler: index.handler
Code:
ZipFile: |
import json
def handler(event, context):
print(event)
# 处理消息的逻辑
Timeout: 60
Role: !GetAtt MyLambdaFunctionRole.Arn
MyLambdaFunctionRole:
Type: AWS::IAM::Role
Properties:
RoleName: MyLambdaFunctionRole
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: MyLambdaFunctionPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- sqs:SendMessage
Resource: !GetAtt MyQueue.Arn
Outputs:
QueueURL:
Value: !Ref MyQueue
Description: URL of the created queue
LambdaFunctionArn:
Value: !GetAtt MyLambdaFunction.Arn
Description: ARN of the created Lambda function
import boto3
def update_lambda_trigger(event, context):
queue_url = event['QueueUrl'] # 从事件中获取队列URL
lambda_client = boto3.client('lambda')
lambda_function_arn = 'arn:aws:lambda:us-west-2:123456789012:function:MyLambdaFunction' # 替换为你的Lambda函数ARN
# 更新Lambda触发器
lambda_client.update_event_source_mapping(
UUID='YOUR_EVENT_SOURCE_MAPPING_UUID', # 替换为之前创建的触发器的UUID
FunctionName=lambda_function_arn,
Enabled=True,
BatchSize=10,
EventSourceArn=queue_url,
StartingPosition='LATEST'
)
import boto3
def recreate_queue():
queue_name = 'MyQueue' # 替换为你的队列名
sqs_client = boto3.client('sqs')
# 删除队列
sqs_client.delete_queue(
QueueUrl='YOUR_QUEUE_URL' # 替换为你的队列URL
)
# 创建队列
response = sqs_client.create_queue(
QueueName=queue_name
)
queue_url = response['QueueUrl']
lambda_client = boto3.client('lambda')
lambda_function_arn = 'arn:aws:lambda:us-west-2:123456789012:function:MyLambdaFunction' # 替换为你的Lambda函数ARN
# 更新Lambda触发器
lambda_client.update_event_source_mapping(
UUID='YOUR_EVENT_SOURCE_MAPPING_UUID', # 替换为之前创建的触发器的UUID
FunctionName=lambda_function_arn,
Enabled=True,
BatchSize=10,
EventSourceArn=queue_url,
StartingPosition='LATEST'
)
请注意,代码示例中的一些值需要根据你的实际情况进行替换,例如队列名、Lambda函数ARN、队列URL和触发器的UUID。
这样,当队列被删除并重新创建时,你可以手动调用recreate_queue()函数来重新创建队列并更新触发