Component to Simplify Using the AWS SDK for Consuming the SQS Messaging Service in .NET Core Projects
First, This component does not use AWS Access Key ID and Secret Access Key to consume the SQS queue on localhost. To be able to consume it is necessary to be logged first in to AWS through the AWS CLI. Installing or updating the latest version of the AWS CLI.
The component uses two parameters to access or send a message to the SQS queue, for that add the access environment variables to your queue
In launchSettings.json
:
{
"profiles": {
"environmentVariables": {
"AWS_REGION": "us-east-1",
"AWS_ACCOUNT_ID": "000000000000"
},
}
}
OR
via code startup.cs
:
Environment.SetEnvironmentVariable("AWS_REGION", "us-east-1");
Environment.SetEnvironmentVariable("AWS_ACCOUNT_ID", "000000000000");
Inject the dependency directly into your IServiceCollection of type AddSingleton as shown below
services.AddSingleton<IMessagingAsync, CataldiMessagingSQS>();
Get the interface in the constructor
private readonly IMessagingAsync _messagingAsync;
public Constructor(IMessagingAsync messageasync)
{
_messagingAsync = messageasync;
}
This method returns all messages informed in the third and second parameter. The second parameter is the number of messages and the third is the waiting time The code below return 5 messages with a wait time of 10 seconds
var messages = _messagingAsync.GetMessages("queue-name", 5, 10).GetAwaiter().GetResult();
if (messages.Any())
{
foreach (var message in messages)
{
var queueMessage = message.Body;
// IMPLEMENT YOUR CODE HERE
}
}
This method waits for a message to be sent to the queue, by default the maximum time allowed by AWS is 20 seconds.
var messages = await _messagingAsync.ReceiveMessagesAsync(_initialRegistrationQueue, 20);
This method sends a message to the specified queue
await _messagingAsync.SendMessage("queue-name", "YOUR-MESSAGE");
if (messages.Any())
{
foreach (var message in messages)
{
var queueMessage = message.Body;
// IMPLEMENT YOUR CODE HERE
}
}
Method responsible for removing the message from the queue
_messagingAsync.AckMessage("queue-name", message).GetAwaiter().GetResult();
SQS usage documentation: Amazon Simple Queue Service Documentation SQS usage documentation: AWS Identity and Access Management Documentation
@dicataldisky |
---|