RetailSolutions.Shared.Events 1.3.1381

dotnet add package RetailSolutions.Shared.Events --version 1.3.1381
                    
NuGet\Install-Package RetailSolutions.Shared.Events -Version 1.3.1381
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RetailSolutions.Shared.Events" Version="1.3.1381" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RetailSolutions.Shared.Events" Version="1.3.1381" />
                    
Directory.Packages.props
<PackageReference Include="RetailSolutions.Shared.Events" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RetailSolutions.Shared.Events --version 1.3.1381
                    
#r "nuget: RetailSolutions.Shared.Events, 1.3.1381"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RetailSolutions.Shared.Events@1.3.1381
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RetailSolutions.Shared.Events&version=1.3.1381
                    
Install as a Cake Addin
#tool nuget:?package=RetailSolutions.Shared.Events&version=1.3.1381
                    
Install as a Cake Tool

RetailSolutions.Shared.Events

NuGet .NET License

Biblioteca .NET para comunicação assíncrona via RabbitMQ, com abstrações de alto nível para publicação e consumo de mensagens em arquiteturas de microsserviços.


Sumário


Recursos

Recurso Descrição
Consumer / Publisher independentes Abstrações desacopladas para consumo e publicação
Conexão persistente Gerenciamento automático de conexões com reconexão configurável
Resiliência com Polly Retry automático com política de backoff exponencial
Dead Letter Queue (DLQ) Suporte nativo para captura de mensagens com falha
Validação de startup Extensões UseConsumer / UsePublisher para garantir conexão antes de servir tráfego
Integração .NET nativa Suporte a WebApplication, IHost e injeção de dependência

Requisitos

  • .NET 10.0 ou superior
  • RabbitMQ Server 3.8 ou superior
  • Microsoft.AspNetCore.App

Instalação

dotnet add package RetailSolutions.Shared.Events

Início Rápido

Consumer

1. Registrar o consumer no Program.cs:

using RetailSolutions.Shared.Events;

var builder = WebApplication.CreateBuilder(args);

builder.AddConsumer<OrderCreatedHandler>(new ConsumerOptions
{
    ConnectionString = "amqp://guest:guest@localhost:5672",
    ApplicationName  = "OrderService",
    QueueName        = "orders",
    ExchangeName     = "orders-exchange",
    RoutingKey       = "#",
    ConfigureDlq     = true
});

var app = builder.Build();

app.UseConsumer(); // valida a conexão no startup
app.Run();

2. Implementar o handler:

public class OrderCreatedHandler : IRabbitMQMessageHandler
{
    private readonly ILogger<OrderCreatedHandler> _logger;

    public OrderCreatedHandler(ILogger<OrderCreatedHandler> logger)
        => _logger = logger;

    public async Task<bool> HandleAsync(RabbitMQMessageEventArgs args)
    {
        _logger.LogInformation("Message received. RoutingKey: {Key}", args.RoutingKey);

        // var order = JsonSerializer.Deserialize<OrderCreatedEvent>(args.Body);

        // Retorna true  → ACK  (mensagem processada com sucesso)
        // Retorna false → NACK (mensagem rejeitada / reenfileirada)
        return true;
    }
}

Publisher

1. Registrar o publisher:

builder.AddPublisher(new PublisherOptions
{
    ConnectionString = "amqp://guest:guest@localhost:5672",
    ApplicationName  = "OrderService",
    ExchangeName     = "orders-exchange",
    Persistent       = true
});

var app = builder.Build();

app.UsePublisher(); // valida a conexão no startup
app.Run();

2. Publicar mensagens via injeção de dependência:

public class OrderService(IRabbitMQPublisher publisher)
{
    public async Task CreateOrderAsync(Order order)
    {
        // Publicar string simples
        await publisher.PublishAsync("order.created", "Order created");

        // Publicar objeto (serializado automaticamente para JSON)
        await publisher.PublishAsync("order.created", new OrderCreatedEvent
        {
            OrderId      = order.Id,
            CustomerName = order.CustomerName,
            TotalAmount  = order.Total
        });

        // Publicar com headers customizados
        await publisher.PublishAsync("order.created", order, new Dictionary<string, object>
        {
            ["source"]  = "OrderService",
            ["version"] = "1.0"
        });
    }
}

Configuração via appsettings.json

{
  "RabbitMQ": {
    "Consumer": {
      "ConnectionString": "amqp://guest:guest@localhost:5672",
      "ApplicationName": "OrderService",
      "QueueName": "orders",
      "ExchangeName": "orders-exchange",
      "RoutingKey": "#",
      "RetryPolicy": 5,
      "EnableAutoReconnect": true,
      "ConfigureDlq": true
    },
    "Publisher": {
      "ConnectionString": "amqp://guest:guest@localhost:5672",
      "ApplicationName": "OrderService",
      "ExchangeName": "orders-exchange",
      "Persistent": true
    }
  }
}
builder.AddConsumer<MyHandler>();          // lê "RabbitMQ:Consumer"
builder.AddPublisher();                    // lê "RabbitMQ:Publisher"

// Seção customizada
builder.AddConsumer<MyHandler>("Messaging:RabbitMQ:Consumer");

Referência de API

ConsumerOptions

Propriedade Tipo Padrão Descrição
ConnectionString string amqp://guest:guest@localhost:5672 String de conexão do RabbitMQ
ApplicationName string "Application" Nome da aplicação (consumer tag)
QueueName string "" Nome da fila (vazio = fila temporária)
ExchangeName string "" Nome do exchange
RoutingKey string "#" Routing key para binding
RetryPolicy int 5 Número máximo de tentativas
RetryDelay TimeSpan 5s Intervalo entre tentativas
EnableAutoReconnect bool true Reconexão automática em falhas
ReconnectDelay TimeSpan 10s Intervalo para reconexão
PrefetchCount ushort 1 Mensagens pré-buscadas por vez
ConfigureDlq bool false Habilita Dead Letter Queue
DlqExchangeName string? null Exchange DLQ (auto-gerado se vazio)
DlqQueueName string? null Fila DLQ (auto-gerado se vazio)
DlqRoutingKey string "#" Routing key para DLQ
Durable bool true Fila/exchange duráveis
Exclusive bool false Fila exclusiva da conexão
AutoDelete bool false Auto-deletar quando sem consumers

PublisherOptions

Propriedade Tipo Padrão Descrição
ConnectionString string amqp://guest:guest@localhost:5672 String de conexão do RabbitMQ
ApplicationName string "Application" Nome da aplicação
ExchangeName string "" Nome do exchange
RetryPolicy int 5 Número máximo de tentativas
RetryDelay TimeSpan 5s Intervalo entre tentativas
EnableAutoReconnect bool true Reconexão automática em falhas
ReconnectDelay TimeSpan 10s Intervalo para reconexão
Durable bool true Exchange durável
AutoDelete bool false Auto-deletar quando sem bindings
Mandatory bool false Retorna erro se nenhuma fila receber a mensagem
Persistent bool true Mensagens gravadas em disco

Exemplos Avançados

Consumer em Console App (IHost)

var builder = Host.CreateApplicationBuilder(args);

builder.AddConsumer<MyHandler>(new ConsumerOptions
{
    ConnectionString = "amqp://guest:guest@localhost:5672",
    ApplicationName  = "ConsoleApp",
    QueueName        = "console-queue",
    ExchangeName     = "console-exchange"
});

var host = builder.Build();
await host.RunAsync();

Publisher em Console App

var builder = Host.CreateApplicationBuilder(args);

builder.AddPublisher(new PublisherOptions
{
    ConnectionString = "amqp://guest:guest@localhost:5672",
    ApplicationName  = "ConsoleApp",
    ExchangeName     = "console-exchange"
});

var host = builder.Build();
var publisher = host.Services.GetRequiredService<IRabbitMQPublisher>();

await publisher.PublishAsync("test.message", "Hello from console app!");
await host.RunAsync();

Validação de conexão no startup

// Lança exceção se não conectar dentro do timeout
app.UseConsumer(timeout: TimeSpan.FromSeconds(60), throwOnFailure: true);

// Apenas loga warning se não conectar (não bloqueia a inicialização)
app.UsePublisher(timeout: TimeSpan.FromSeconds(60), throwOnFailure: false);

Dead Letter Queue

builder.AddConsumer<MyHandler>(new ConsumerOptions
{
    // ...
    ConfigureDlq     = true,
    DlqExchangeName  = "orders-exchange.dlx",  // opcional, auto-gerado se omitido
    DlqQueueName     = "orders.dlq",           // opcional, auto-gerado se omitido
    DlqRoutingKey    = "#"
});

Estrutura do Projeto

RetailSolutions.Shared.Events/
├── IEventBus.cs
├── IntegrationEvent.cs
└── RabbitMQ/
    ├── Interfaces & Models
    │   ├── IRabbitMQConsumer.cs
    │   ├── IRabbitMQMessageHandler.cs
    │   ├── IRabbitMQPublisher.cs
    │   ├── RabbitMQMessageEventArgs.cs
    │   ├── ConsumerOptions.cs
    │   └── PublisherOptions.cs
    ├── Base
    │   └── RabbitMQConnectionBase.cs
    ├── Implementations
    │   ├── RabbitMQConsumer.cs
    │   ├── RabbitMQConsumerService.cs
    │   └── RabbitMQPublisher.cs
    └── Extensions
        ├── RabbitMQConsumerExtensions.cs
        └── RabbitMQPublisherExtensions.cs

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on RetailSolutions.Shared.Events:

Package Downloads
RetailSolutions.Shared.Notifications

Abstrações para publicação de notificações via RabbitMQ

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.1381 157 7/6/2026
1.2.109 110 4/30/2026
1.2.103 129 2/13/2026
1.2.102 122 2/13/2026
1.2.101 119 2/13/2026
1.2.97 210 2/13/2026
1.2.96 128 2/13/2026
1.2.95 133 1/31/2026
1.2.88 594 12/13/2025
1.2.87 195 12/13/2025
1.2.86 195 12/13/2025
1.2.80 217 12/13/2025
1.2.75 148 12/12/2025