<func-name>
import json
import boto3
import random
def lambda_handler(event, context):
sqs = boto3.client('sqs')
queue_url = '<YOUR_QUEUE_URL>'
# Generate multiple messages for different orders
orders = [
{"orderId": str(random.randint(10000, 99999)), "product": "Book", "quantity": 1},
{"orderId": str(random.randint(10000, 99999)), "product": "Laptop", "quantity": 2},
{"orderId": str(random.randint(10000, 99999)), "product": "Headphones", "quantity": 1},
{"orderId": str(random.randint(10000, 99999)), "product": "Camera", "quantity": 1},
]
for order in orders:
# Send each order as a message
response = sqs.send_message(
QueueUrl=queue_url,
MessageBody=json.dumps(order)
)
print(f"Sent order {order['orderId']} - Response: {response['MessageId']}")
return {
'statusCode': 200,
'body': json.dumps('All orders sent successfully!'),
'orders: ' : orders
}
<func-name>
import json
import boto3
import random
def lambda_handler(event, context):
sqs = boto3.client('sqs')
queue_url = '<YOUR_QUEUE_URL>'
# List of available delivery trucks
delivery_trucks = ['Truck-1', 'Truck-2', 'Truck-3', 'Truck-4']
# Randomly choose the number of messages to process (between 1 and 4)
num_messages_to_process = random.randint(1, 4)
# Poll messages (up to the randomly chosen number)
response = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=num_messages_to_process,
WaitTimeSeconds=10
)
messages = response.get('Messages', [])
if not messages:
return {
'statusCode': 200,
'body': 'No messages to process.'
}
# Store processed order details for the response
processed_orders = []
for message in messages:
order = json.loads(message['Body'])
# Randomly assign the order to a delivery truck
assigned_truck = random.choice(delivery_trucks)
# Record the processed order details
processed_order = {
"orderId": order['orderId'],
"product": order['product'],
"quantity": order['quantity'],
"assignedTruck": assigned_truck
}
processed_orders.append(processed_order)
# Simulate order processing log
print(f"Order {processed_order['orderId']} - Product: {processed_order['product']} "
f"(Quantity: {processed_order['quantity']}) has been assigned to {processed_order['assignedTruck']} "
f"for delivery.")
# Delete the message from the queue after processing
sqs.delete_message(
QueueUrl=queue_url,
ReceiptHandle=message['ReceiptHandle']
)
# Return the response as a dictionary to avoid escape characters
return {
'statusCode': 200,
'body': {
'message': 'Processed random orders and assigned to delivery trucks!',
'processedOrders': processed_orders
}
}
<name-of-topic>
<func-name>
import json
def lambda_handler(event, context):
# Print the event received from SNS
print("Received event from SNS:")
print(json.dumps(event, separators=(',', ':')))
# Process each record in the event
for record in event['Records']:
# Access the SNS message inside the Sns object
sns_message = record['Sns']['Message']
print(f"Processing SNS message: {sns_message}")
return {
'statusCode': 200,
'body': json.dumps('Messages processed successfully!')
}
<subject-test>
<message-body>
Processing SNS message
<queue-name>
<dlq-name>
<func-name>
import json
def lambda_handler(event, context):
# Simulate failure by always returning an error
print("Simulating message processing failure")
raise Exception("Processing failed")
## Observe Messages in the DLQ
<queue-name>
<func-name>
import time
def lambda_handler(event, context):
for record in event['Records']:
print("Processing message:", record['body'])
time.sleep(45) # Simulate processing delay (longer than visibility timeout)
print("Finished processing")
import json
def lambda_handler(event, context):
for record in event['Records']:
print("Successfully processed message:", record['body'])
return {
'statusCode': 200,
'body': 'Success'
}
<topic-name>
<subject-title>
<message-body>
<subject-description>
<message>
<Topic-Name.fifo>
<Queue-Name.fifo>
<Queue-Name.fifo>
{
"Version": "2012-10-17",
"Id": "QueuePolicy",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "sqs:SendMessage",
"Resource": "arn:aws:sqs:<region>:<account-id>:MyFifoQueue.fifo",
"Condition": {
"ArnEquals": {
"aws:SourceArn": "arn:aws:sns:<region>:<account-id>:MyFifoTopic.fifo"
}
}
}
]
}