Select your cookie preferences

We use cookies and similar tools to enhance your experience, provide our services, deliver relevant advertising, and make improvements. Approved third parties also use these tools to help us deliver advertising and provide certain site features.

Amazon Simple Queue Service (SQS), AWS Lambda Function & Amazon DynamoDB

This project contains an AWS Lambda function that consumes messages from an Amazon Simple Queue Service (Amazon SQS) and inserts them to Amazon DynamoDB using SAM and .NET 6.


Files:

Application Code

using System;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using AWS.Lambda.Powertools.Logging;
using AWS.Lambda.Powertools.Tracing;
using Microsoft.Extensions.DependencyInjection;
using SqsEventHandler.Handlers;
using SqsEventHandler.Infrastructure;
using SqsEventHandler.Models;
using SqsEventHandler.Repositories;
using SqsEventHandler.Repositories.Models;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SqsEventHandler.Functions;

/// 
/// This class implements the business logic of the function. The function handler can be found in
/// the base abstract class SqsEventHandler::Handler
/// 
public class ProcessEmployeeFunction : SqsEventHandler
{
    private readonly IDynamoDbRepository _employeeRepository;

    public ProcessEmployeeFunction()
    {
        _employeeRepository = ServiceProvider.GetRequiredService>();
    }

    public ProcessEmployeeFunction(IDynamoDbRepository employeeRepository)
    {
        _employeeRepository = employeeRepository;
    }

    [Tracing(SegmentName = "ProcessEmployeeFunction")]
    public override async Task ProcessSqsMessage(Employee message, ILambdaContext lambdaContext)
    {
        if (message == null)
            throw new ArgumentNullException(nameof(message));
        if (message.EmployeeId == null)
            throw new ArgumentNullException(nameof(message.EmployeeId));

        using var cts = lambdaContext.GetCancellationTokenSource();

        var response = await _employeeRepository.PutItemAsync(message.AsDto(), cts.Token);

        Logger.LogInformation($"{response}, {message}");
    }
}
                                                  


GitHub icon Visit the GitHub repo for this pattern.

Clone locally

git clone https://github.com/aws-samples/serverless-patterns/ cd dotnet-test-samples/sqs-lambda

Authors

Leslie Daniel Raj Cloud Application Architect at AWS
Leslie Daniel Raj

Presented by Leslie Daniel Raj

Cloud Application Architect at AWS

Follow on LinkedIn