以下是一个简单的Lambda函数示例,代码实现了从SQS队列中获取消息并给接收者发送的过程:
import boto3
import json
def lambda_handler(event, context):
sqs = boto3.resource('sqs')
queue = sqs.get_queue_by_name(QueueName='my_queue')
messages = queue.receive_messages(
MaxNumberOfMessages=1,
WaitTimeSeconds=5
)
for message in messages:
# Parse the message body
body = json.loads(message.body)
# Check if recipient is online
if is_online(body['recipient']):
# Send the message directly to the recipient
send_message(body['recipient'], body['text'])
else:
# Write the message to DynamoDB for later retrieval
write_to_dynamodb(body)
# Delete the message from the queue
message.delete()