QuickStart - velviagris/NanoRabbit GitHub Wiki

Catalog

Note

NanoRabbit is designed as a library depends on NAMING Connections, Producers, Consumers. So it's important to set a UNIQUE NAME for each Connections, Producers, Consumers.

How to use

Follow these steps to start using NanoRabbit:

  1. Setup RabbitConnections
  2. Add RabbitHelpers
  3. Add MessageHandlers for Consumers
  4. Add RabbitConsumers

Setup Connections && Helpers && RabbitConsumers

Setup connections

Before using NanoRabbit, you should register IConnection and other configs by calling AddRabbitConnection( this IServiceCollection services, Action<RabbitConfigurationBuilder> builder)

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NanoRabbit;
using NanoRabbit.DependencyInjection;

var builder = Host.CreateApplicationBuilder(args);

// Configure the RabbitMQ Connection
builder.Services.AddRabbitConnection(x =>
    {
        x.SetHostName("localhost")
            .SetPort(5672)
            .SetVirtualHost("/")
            .SetUserName("admin")
            .SetPassword("admin")
            .SetConnectionName("FooConnection")
            .AddProducerOption(producer =>
            {
                producer.ProducerName = "FooProducer";
                producer.ExchangeName = "amq.topic";
                producer.RoutingKey = "foo.key";
                producer.Type = ExchangeType.Topic;
            })
            .AddConsumerOption(consumer =>
            {
                consumer.ConsumerName = "FooConsumer";
                consumer.QueueName = "foo-queue";
                consumer.ConsumerCount = 3;
                consumer.HandlerName = nameof(FooQueueHandler);
            })
            .AddConsumerOption(consumer =>
            {
                consumer.ConsumerName = "BarConsumer";
                consumer.QueueName = "bar-queue";
                consumer.ConsumerCount = 2;
                consumer.HandlerName = nameof(BarQueueHandler);
            });
    });

// todo: Add RabbitHelpers and RabbitCnsumers if neccessary.

using IHost host = builder.Build();

host.Run();

Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();

Add Consumers

Register a RabbitMQ Consumer by calling AddRabbitAsyncHandler<TAsyncHandler>() and AddRabbitConsumer(), you should declare HandlerName at the previous settings of RabbitConnection.

// Register the connection like before
builder.Services.AddRabbitConnection(x=>{});

// Register IAsyncHandler and RabbitConsumer
builder.Services.AddRabbitAsyncHandler<FooQueueHandler>()
    .AddRabbitAsyncHandler<BarQueueHandler>()
    .AddRabbitConsumer();

// Build and run the host
using IHost host = builder.Build();
host.Run();

When the host starts running, it will start some BackgroundService to start consuming.

Publish Messages

After registering RabbitConnection, you should register RabbitHelper, then you can simply publish a message by calling PublishAsync<T>(string producerName, T message).

// Register the connection like before
builder.Services.AddRabbitConnection(x=>{});

// Register a RabbitHelper
builder.Services.AddRabbitHelper();

// Build and run the host
using IHost host = builder.Build();
host.Run();

var rabbitMqHelper = host.Services.GetRequiredService<IRabbitHelper>();
await rabbitMqHelper.PublishAsync("FooProducer", "Hello, World!");

Consume Messages

After registering a RabbitConsumer, you should complete the TAsyncHandler, which is declared in AddRabbitConnection(x=>{}) and being registered by calling AddRabbitAsyncHandler<TAsyncHandler>().

For example:

public class FooQueueHandler : IAsyncMessageHandler
{
    public async Task HandleMessageAsync(byte[] messageBody, string? routingKey = null, string? correlationId = null)
    {
        var message = Encoding.UTF8.GetString(messageBody);
        Console.WriteLine($"[x] Received from foo-queue: {message}");
        await Task.Delay(1000);
        Console.WriteLine("[x] Done");
    }
}

Inherit IAsyncMessageHandler and implement Task HandleMessageAsync(byte[] messageBody, string? routingKey = null, string? correlationId = null).

Recommend