From 6186fe799242039743c101ff28366794b2642e09 Mon Sep 17 00:00:00 2001 From: Jonathon Frame <42950310+jon-frame@users.noreply.github.com> Date: Mon, 12 Oct 2020 12:40:49 +1100 Subject: [PATCH] Created alternate function Existing function does not leverage the SQS messages in the lambda event and instead polls the queue again, meaning once function gets up to speed with concurrent invocations, the queue is perpetually empty: only 5-7 messages make it into DynamoDB, then no more. This fix instead uses the Lambda event to push messages into DynamoDB. --- .../sqs_lambda_function.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Triggering-Lambda-from-SQS/sqs_lambda_function.py diff --git a/Triggering-Lambda-from-SQS/sqs_lambda_function.py b/Triggering-Lambda-from-SQS/sqs_lambda_function.py new file mode 100644 index 0000000..4573f48 --- /dev/null +++ b/Triggering-Lambda-from-SQS/sqs_lambda_function.py @@ -0,0 +1,29 @@ +from datetime import datetime +import json +import os +import boto3 + +DYNAMODB_TABLE = os.environ['DYNAMODB_TABLE'] + +dynamodb = boto3.resource('dynamodb') + +def lambda_handler(event, context): + # Count items in the Lambda event + no_messages = str(len(event['Records'])) + print("Found " +no_messages +" messages to process.") + + for message in event['Records']: + + print(message) + + # Write message to DynamoDB + table = dynamodb.Table(DYNAMODB_TABLE) + + response = table.put_item( + Item={ + 'MessageId': message['messageId'], + 'Body': message['body'], + 'Timestamp': datetime.now().isoformat() + } + ) + print("Wrote message to DynamoDB:", json.dumps(response))