首先,确保您正确配置了 CloudWatch 事件。请检查 CloudWatch 事件规则并确认它正确指向您的 SQS 队列。
然后,请检查您的 SQS 队列权限。确保您的 CloudWatch 事件执行角色或用户具有向该队列发送消息的权限。
接下来,请检查您的 Lambda 函数。如果您使用 Lambda 函数作为 CloudWatch 事件的目标,则应确认该函数能够正确地处理 SQS 消息,并且该角色或用户具有从 SQS 队列接收消息的权限。
以下是一个使用 CloudWatch 事件触发 SQS 的示例代码:
import boto3
# Configure the client
sqs_client = boto3.client('sqs')
# Set the queue URLs and Event Rule Names
queue_url = 'your_sqs_queue_url'
event_rule_name = 'your_event_rule_name'
# Get the event rule
event_rule_arn = ''
for rule in boto3.client('events').list_rules()['Rules']:
if rule['Name'] == event_rule_name:
event_rule_arn = rule['Arn']
break
# Get the SQS queue attributes
queue_attributes = sqs_client.get_queue_attributes(
QueueUrl=queue_url,
AttributeNames=['All']
)
# Build the Event rule target
target = {
'Id': 'sqs-queue',
'Arn': queue_url,
'RoleArn': 'your_sqs_role_arn'
}
# Set the Event Rule
boto3.client('events').put_targets(
Rule=event_rule_arn,
Targets=[target]
)
# Set the SQS queue permissions
sqs_client.add_permission(
QueueUrl=queue_url,
Label='lambda-permission',
AWSAccountId=[
'your_lambda_role_account_id'
],
ActionNames=[
'SendMessage',
'ReceiveMessage',
'DeleteMessage'
]
)
这将为您设置一个 CloudWatch 事件规则,该规则将 SQS 队列作为目标,并