Giter Site home page Giter Site logo

nuages-io / nuages-queue Goto Github PK

View Code? Open in Web Editor NEW
3.0 1.0 0.0 1001 KB

Nuages.Queue is a .NET Core C# library that provides functionalities to poll and process message from a queue.

License: Apache License 2.0

C# 92.48% HTML 4.30% CSS 2.65% JavaScript 0.57%
queue aws sqs azure-storage-queue dotnetcore

nuages-queue's Introduction

Nuages.Queue

Nuages.Queue Nuages.Queue Nuages.Queue

example workflow

Nuages.Queue introduce the QueryWorker abstract class which is responsible to get message from a queue. The class needs to inherit from QueueWorker<> in order to provide overload for queue manipulations.

Two pre-build packages are available on nuget :

Using Nuages.Queue.SQS

See Nuages.Queue.Samples.SQS.Console for a full working sample.

Follow those steps to use Nuages.Queue.SQS in your .NET 6 console project.

  1. Create the project
dotnet new console -n Nuages.Queue.Samples.SQS.Console
cd Nuages.Queue.Samples.SQS.Console
  1. Add a package reference to Nuages.Queue.SQS
dotnet add package Nuages.Queue.SQS 
  1. Change the Project Sdk to Microsoft.NET.Sdk.Worker
<Project Sdk="Microsoft.NET.Sdk.Worker">
  1. Add other references to the .csproj
<ItemGroup>
  <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="3.7.1" />
  <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
  <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
  <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
  <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
  <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
</ItemGroup>
  1. Optional. Add a new appsettings.json configuration file and set SQS credential info.
{
  "Queues":
  {
    "AutoCreateQueue" : true
  },
  "QueueWorker" :
  {
    "QueueName" : "queue-name-goes-here",
    "Enabled" : true,
    "MaxMessagesCount" : 1,
    "WaitDelayInMillisecondsWhenNoMessages": 2000
  }
}
  1. Create your worker class. The following sample worker output message to the console.
using Microsoft.Extensions.Options;
using Nuages.Queue.SQS;

namespace Nuages.Queue.Samples.SQS.Console;

// ReSharper disable once ClassNeverInstantiated.Global
public class SampleWorker : QueueWorker<ISQSQueueService>
{
    private readonly ILogger<QueueWorker<ISQSQueueService>> _logger;

    public SampleWorker(IServiceProvider serviceProvider, ILogger<SampleWorker> logger, IOptions<QueueWorkerOptions> options) : base(serviceProvider, logger, options)
    {
        _logger = logger;
    }

    protected override async Task<bool> ProcessMessageAsync(QueueMessage msg)
    {
        await Task.Run(() =>
        {
            _logger.LogInformation("Message : {Message}", msg.Body);
            
            System.Console.WriteLine(msg.Body);

        });
       
        return true;
    }
} 
  1. Finally, add the following code to your Program.cs file
using Amazon;
using Amazon.Runtime;
using Amazon.SQS;
using Microsoft.Extensions.Options;
using Nuages.Queue;
using Nuages.Queue.Samples.SQS.Console;
using Nuages.Queue.SQS;

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetParent(AppContext.BaseDirectory)?.FullName)
    .AddJsonFile("appsettings.json", true)
    .AddJsonFile("appsettings.local.json", true)
    .Build();

var hostBuilder = new HostBuilder()
    .ConfigureLogging(logging => { logging.AddConsole(); })
    .ConfigureServices(services =>
        {
            services
                .AddSingleton(configuration)
                .AddQueueWorker<SampleWorker>(configuration);

            AddSQS(services);
        }
    );

var host = hostBuilder.UseConsoleLifetime().Build();

await SendTestMessageAsync(host.Services);

await host.RunAsync();

async Task SendTestMessageAsync(IServiceProvider provider)
{
    var queueService = provider.GetRequiredService<ISQSQueueService>();
    var options = provider.GetRequiredService<IOptions<QueueWorkerOptions>>().Value;

    var  fullName = await queueService.GetQueueFullNameAsync(options.QueueName);
    await queueService.EnqueueMessageAsync(fullName!, "Started!!!");
}

// ReSharper disable once InconsistentNaming
void AddSQS(IServiceCollection services, bool useProfile = true)
{
    if (useProfile)
    {
        //By default, we use a SQS profile to get credentials https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html
        services.AddDefaultAWSOptions(configuration.GetAWSOptions())
            .AddAWSService<IAmazonSQS>();
    }
    else
    {
        var section = configuration.GetSection("SQS");
        var accessKey = section["AccessKey"];
        var secretKey = section["SecretKey"];
        var region = section["Region"];

        var sqsClient = new AmazonSQSClient(new BasicAWSCredentials(accessKey, secretKey),
            RegionEndpoint.GetBySystemName(region));

        services.AddSingleton<IAmazonSQS>(sqsClient);
    }
}

Using Nuages.Queue.ASQ

The code is similar to the SQS sample.

See Nuages.Queue.Samples.ASQ.Console for a full working sample.

nuages-queue's People

Contributors

martin-masse avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

nuages-queue's Issues

And I’m trying to setup multi queue workers for different queues but something like this doesn’t work.

Hi Martin,

I’m using the following library:

https://github.com/nuages-io/nuages-queue

And I’m trying to setup multi queue workers for different queues but something like this doesn’t work.

   services.AddQueueWorker<LoginEventWorker>(configuration).Configure<QueueWorkerOptions>(options =>

        {

            options.QueueName = "login-event";

        });



        services.AddQueueWorker<RegistrationEventWorker>(configuration).Configure<QueueWorkerOptions>(options =>

        {

            options.QueueName = "customer_registration";

        });

The LoginEventWorker keeps pickup the ‘customer_registration’ queue name. I can’t see how this would work for multi queues…

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.