### Install RabbitMQCoreClient via NuGet Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Use the PowerShell command to add the library to your project. ```powershell Install-Package RabbitMQCoreClient ``` -------------------------------- ### Initialize RabbitMQCoreClient in Console Application Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Setup dependency injection and connect to the broker for message publishing in a console environment. ```csharp using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using RabbitMQCoreClient; using RabbitMQCoreClient.DependencyInjection; Console.WriteLine("Simple console message publishing only example"); var config = new ConfigurationBuilder() .AddJsonFile($"appsettings.json", optional: false) .AddJsonFile($"appsettings.Development.json", optional: true) .Build(); var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(LoggerFactory.Create(x => { x.SetMinimumLevel(LogLevel.Trace); x.AddConsole(); })); // Just for sending messages. services.AddRabbitMQCoreClient(config.GetSection("RabbitMQ")); var provider = services.BuildServiceProvider(); var publisher = provider.GetRequiredService(); await publisher.ConnectAsync(); await publisher.SendAsync("""{ "foo": "bar" }""", "test_key"); ``` -------------------------------- ### Configure Flush Settings via JSON Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Example configuration for defining flush periods and counts. ```json { "QueueFlushSettings": { "EventsFlushPeriodSec": 2, "EventsFlushCount": 500 } } ``` -------------------------------- ### Configure Custom Serializer in Program.cs Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Example of how to register a custom serializer during application startup in a console application. ```csharp services .AddRabbitMQCoreClient(config) .AddCustomSerializer(); ``` -------------------------------- ### Implement IEventsWriter Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Example implementation of the IEventsWriter interface for custom batch processing. ```csharp namespace RabbitMQCoreClient.BatchQueueSender; /// /// Implementation of the service for sending events to the data bus. /// internal sealed class EventsWriter : IEventsWriter { readonly IQueueService _queueService; /// /// Create new object of . /// /// Queue publisher. public EventsWriter(IQueueService queueService) { _queueService = queueService; } /// public async Task WriteBatch(IEnumerable events, string routingKey) { if (!events.Any()) return; await _queueService.SendBatchAsync(events.Select(x => x.Message), routingKey); } } ``` -------------------------------- ### Implement IMessageHandler for raw bytes Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Provides an example of implementing a custom message handler to process raw byte data and metadata from RabbitMQ. ```csharp using RabbitMQCoreClient; using RabbitMQCoreClient.Models; public class RawMessageHandler : IMessageHandler { private readonly ILogger _logger; public RawMessageHandler(ILogger logger) { _logger = logger; } public Task HandleMessage( ReadOnlyMemory message, RabbitMessageEventArgs args, MessageHandlerContext context) { // Access raw message bytes var messageString = System.Text.Encoding.UTF8.GetString(message.Span); _logger.LogInformation("Received message: {Message}", messageString); // Access message metadata _logger.LogInformation("Routing key: {RoutingKey}", args.RoutingKey); _logger.LogInformation("Exchange: {Exchange}", args.Exchange); _logger.LogInformation("DeliveryTag: {DeliveryTag}", args.DeliveryTag); // Message will be acknowledged automatically on successful completion return Task.CompletedTask; } } // Registration services.AddRabbitMQCoreClientConsumer(configuration.GetSection("RabbitMQ")) .AddHandler("raw.message.key"); ``` -------------------------------- ### Background Service for Message Consumption Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Implement message consumers as background hosted services for continuous message processing. This setup requires registering RabbitMQ services and defining message handlers. ```csharp using Microsoft.Extensions.Hosting; using RabbitMQCoreClient; using RabbitMQCoreClient.DependencyInjection; // Program.cs var builder = Host.CreateApplicationBuilder(args); builder.Services .AddRabbitMQCoreClientConsumer(builder.Configuration.GetSection("RabbitMQ")) .AddHandler("notification.send") .AddHandler("email.send") .AddQueue("notifications_queue") .AddSubscription(); // Creates exclusive auto-delete queue for pub/sub var host = builder.Build(); await host.RunAsync(); // Handlers are automatically started by RabbitMQHostedService public class NotificationHandler : MessageHandlerJson { private readonly INotificationService _notificationService; private readonly ILogger _logger; public NotificationHandler( INotificationService notificationService, ILogger logger) { _notificationService = notificationService; _logger = logger; } protected override JsonTypeInfo GetSerializerContext() => NotificationContext.Default.NotificationMessage; protected override async Task HandleMessage( NotificationMessage message, RabbitMessageEventArgs args, MessageHandlerContext context) { _logger.LogInformation("Sending notification to {UserId}", message.UserId); await _notificationService.SendAsync(message); } } public class NotificationMessage { public string UserId { get; set; } public string Title { get; set; } public string Body { get; set; } } [JsonSerializable(typeof(NotificationMessage))] public partial class NotificationContext : JsonSerializerContext { } ``` -------------------------------- ### Configure and use IQueueBufferService Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Shows how to register the buffered sender via code or configuration and use it to add events to a memory buffer. ```csharp // Program.cs - Register buffered batch sender using RabbitMQCoreClient.DependencyInjection; using RabbitMQCoreClient.BatchQueueSender; services.AddRabbitMQCoreClient(configuration.GetSection("RabbitMQ")) .AddBatchQueueSender(opt => { opt.EventsFlushPeriodSec = 2; // Flush every 2 seconds opt.EventsFlushCount = 500; // Or when 500 messages accumulated }); // Or configure via appsettings.json // { // "QueueFlushSettings": { // "EventsFlushPeriodSec": 2, // "EventsFlushCount": 500 // } // } services.AddRabbitMQCoreClient(configuration.GetSection("RabbitMQ")) .AddBatchQueueSender(configuration.GetSection("QueueFlushSettings")); ``` ```csharp // Usage in service - inject IQueueBufferService instead of IQueueService using RabbitMQCoreClient.BatchQueueSender; public class HighThroughputService { private readonly IQueueBufferService _bufferService; public HighThroughputService(IQueueBufferService bufferService) { _bufferService = bufferService; } public void ProcessEvents(IEnumerable events) { foreach (var evt in events) { // Add to buffer - thread-safe, non-blocking _bufferService.AddEvent(evt, "events.processed"); } // Add string message _bufferService.AddEvent("""{"type":"ping"}""", "heartbeat"); // Add byte array _bufferService.AddEvent(new byte[] { 0x01, 0x02, 0x03 }, "binary.data"); // Add multiple events at once _bufferService.AddEvents(events, "events.bulk"); } } public class EventData { public string EventType { get; set; } public DateTime Timestamp { get; set; } public Dictionary Payload { get; set; } } ``` -------------------------------- ### Configure RabbitMQ via appsettings.json Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Define connection details, queues, exchanges, and subscriptions in a JSON configuration file. ```json { "RabbitMQ": { "HostName": "rabbit-server", "UserName": "user", "Password": "password", "Port": 5672, "VirtualHost": "/", "DefaultTtl": 5, "PrefetchCount": 1, "UseQuorumQueues": false, "MaxBodySize": 16777216, "SslEnabled": true, "SslVersion": "Tls12", "SslServerName": "rabbit-server.example.com", "SslCheckCertificateRevocation": true, "SslCertPath": "/certs/client.pfx", "SslCertPassphrase": "certpass", "Queues": [ { "Name": "orders_queue", "RoutingKeys": ["order.created", "order.updated"], "Durable": true, "Exclusive": false, "AutoDelete": false, "DeadLetterExchange": "dead_letter_exchange", "UseQuorum": false, "Exchanges": ["orders_exchange"] } ], "Subscriptions": [ { "RoutingKeys": ["cache.invalidate"], "DeadLetterExchange": "dead_letter_exchange", "Exchanges": ["notifications_exchange"] } ], "Exchanges": [ { "Name": "orders_exchange", "IsDefault": true, "Type": "direct", "Durable": true, "AutoDelete": false }, { "Name": "notifications_exchange", "Type": "fanout" } ] } } ``` -------------------------------- ### Initialize RabbitMQCoreClient in ASP.NET Core Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Register the client in the service container and map a POST endpoint for sending messages. ```csharp using RabbitMQCoreClient; using RabbitMQCoreClient.DependencyInjection; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Just for sending messages. builder.Services .AddRabbitMQCoreClient(builder.Configuration.GetSection("RabbitMQ")); var app = builder.Build(); // Configure the HTTP request pipeline. app.MapPost("/send", async (IQueueService publisher) => { await publisher.SendAsync("""{ "foo": "bar" }""", "test_key"); return Results.Ok(); }); app.Run(); ``` -------------------------------- ### Configure Consumer via IConfiguration Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Configures a consumer using configuration sections and handler options. ```csharp builder.Services .AddRabbitMQCoreClientConsumer(builder.Configuration.GetSection("RabbitMQ")) .AddHandler(["test_routing_key"], new ConsumerHandlerOptions { RetryKey = "test_routing_key_retry" }) .AddHandler(["test_routing_key_subscription"], new ConsumerHandlerOptions { RetryKey = "test_routing_key_retry" }); ``` -------------------------------- ### Register RabbitMQ Client via Dependency Injection Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Configure the RabbitMQ client using either appsettings.json sections or a fluent programmatic API. ```csharp // Configuration-based setup (appsettings.json) using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using RabbitMQCoreClient; using RabbitMQCoreClient.DependencyInjection; var services = new ServiceCollection(); // Publisher only - reads from IConfiguration services.AddRabbitMQCoreClient(configuration.GetSection("RabbitMQ")); // Publisher with consumer - for receiving messages services.AddRabbitMQCoreClientConsumer(configuration.GetSection("RabbitMQ")) .AddHandler("routing_key_1", "routing_key_2"); // Fluent API setup (programmatic) services.AddRabbitMQCoreClient(opt => { opt.HostName = "localhost"; opt.UserName = "guest"; opt.Password = "guest"; opt.Port = 5672; opt.DefaultTtl = 5; opt.PrefetchCount = 1; }) .AddExchange("my_exchange") .AddConsumer() .AddHandler("routing_key") .AddQueue("my_queue") .AddSubscription(); ``` -------------------------------- ### Configure RabbitMQ via appsettings.json Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Define connection details and exchange settings in the application configuration file. ```json { "HostName": "rabbit-1", "UserName": "user", "Password": "password", "Exchanges": [ { "Name": "direct_exchange", "IsDefault": true } ] } ``` -------------------------------- ### Send batch messages with IQueueService Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Demonstrates sending objects, strings, and byte arrays in batches to specific queues or exchanges. ```csharp using RabbitMQCoreClient; public class BulkOrderService { private readonly IQueueService _queueService; public BulkOrderService(IQueueService queueService) { _queueService = queueService; } public async Task ProcessBulkOrdersAsync() { // Send batch of objects - each serialized to JSON var orders = Enumerable.Range(1, 100) .Select(i => new Order { OrderId = i, CustomerName = $"Customer {i}", Total = i * 10.5m }); await _queueService.SendBatchAsync(orders, "order.bulk.created"); // Send batch of strings var messages = new[] { """{"id":1}""", """{"id":2}""", """{"id":3}""" }; await _queueService.SendBatchAsync(messages, "order.created"); // Send batch of byte arrays var byteMessages = messages.Select(m => System.Text.Encoding.UTF8.GetBytes(m)); await _queueService.SendBatchAsync(byteMessages, "order.created"); // Send batch to specific exchange await _queueService.SendBatchAsync(orders, "order.created", exchange: "orders_exchange"); } } ``` -------------------------------- ### Configure Consumer with Handler Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Configure the RabbitMQ Core Client consumer in Program.cs, registering a handler for specific routing keys. ```csharp services .AddRabbitMQCoreClientConsumer(config.GetSection("RabbitMQ")) .AddHandler("test_key"); // <-- configure handler with routing keys. ``` -------------------------------- ### Full RabbitMQ Client Configuration with SSL Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md This JSON configuration demonstrates how to set up a RabbitMQ client with SSL enabled. It includes all available SSL options and other client configurations like host, user, queues, subscriptions, and exchanges. ```json { "HostName": "rabbit-1", "UserName": "user", "Password": "password", "DefaultTtl": 5, "PrefetchCount": 1, "UseQuorumQueues": false, // Introduced in v5.1.0 "SslEnabled": true, // Introduced in v5.3.0 "SslAcceptablePolicyErrors": "None", // Introduced in v5.3.0 "SslVersion": "None", // Introduced in v5.3.0 "SslServerName": "serverName", // Introduced in v5.3.0 "SslCheckCertificateRevocation": false, // Introduced in v5.3.0 "SslCertPassphrase": "pass", // Introduced in v5.3.0 "SslCertPath": "/certs", // Introduced in v5.3.0 "MaxBodySize": 16777216, // Introduced in v6.1.1 "Queues": [ { "Name": "my_queue1", "RoutingKeys": [ "event1", "my-messaeg" ], "Durable": true, "Exclusive": false, "AutoDelete": false, "DeadLetterExchange": "test_dead_letter", "UseQuorum": false, // Introduced in v5.1.0 "Exchanges": [ "direct_exchange" ], "Arguments": [ { "param": "value" } ] } ], "Subscriptions": [ { "RoutingKeys": [ "event1", "my-messaeg" ], "DeadLetterExchange": "test_dead_letter", "UseQuorum": false, // Introduced in v5.1.0 "Exchanges": [ "direct_exchange" ], "Arguments": [ { "param": "value" } ] } ], "Exchanges": [ { "Name": "direct_exchange", "IsDefault": true, "Type": "direct", "Durable": true, "AutoDelete": false, "Arguments": [ { "param": "value" } ] } ] } ``` -------------------------------- ### Configure System.Text.Json Options Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Customize System.Text.Json serializer options during RabbitMQ Core Client configuration using an extension method. ```csharp builder.Services .AddRabbitMQCoreClient(builder.Configuration.GetSection("RabbitMQ")) .AddSystemTextJson(opt => opt.PropertyNamingPolicy = JsonNamingPolicy.CamelCase); ``` -------------------------------- ### Configure Consumer via Fluent API Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Configures a consumer using the fluent builder pattern. ```csharp builder.Services .AddRabbitMQCoreClient(opt => opt.Host = "localhost") .AddExchange("default") .AddConsumer() .AddHandler("test_routing_key") .AddQueue("my-test-queue") .AddSubscription(); ``` -------------------------------- ### SSL Configuration Parameters Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Details on the configuration options available for enabling and tuning SSL/TLS connections in the RabbitMQ Core Client. ```APIDOC ## SSL Configuration ### Description Configure SSL secured connections by setting the SslEnabled flag and providing specific security parameters. ### Parameters #### Request Body - **SslEnabled** (boolean) - Required - Enables SSL connection. - **SslAcceptablePolicyErrors** (string) - Optional - Comma-separated list of acceptable TLS policy errors (e.g., "RemoteCertificateNotAvailable"). Default: "None". - **SslVersion** (string) - Optional - TLS protocol version (e.g., "None", "Tls12", "Tls13"). Default: "None". - **SslServerName** (string) - Optional - Expected server name for certificate validation. Default: "". - **SslCheckCertificateRevocation** (boolean) - Optional - Whether to check certificate revocation status. Default: false. - **SslCertPassphrase** (string) - Optional - Passphrase for the client certificate. Default: "". - **SslCertPath** (string) - Optional - File system path to the client certificate. Default: "". ### Request Example { "SslEnabled": true, "SslAcceptablePolicyErrors": "None", "SslVersion": "None", "SslServerName": "serverName", "SslCheckCertificateRevocation": false, "SslCertPassphrase": "pass", "SslCertPath": "/certs" } ``` -------------------------------- ### Send Messages using IQueueService Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Use the IQueueService interface to send individual messages or batches to a routing key. ```csharp // A sending mesages service that implements the IQueueService interface. var queueService = serviceProvider.GetRequiredService(); // Send one message to the queue. var body = new SimpleObj { Name = "test sending" }; await queueService.SendAsync(body, "test_routing_key"); // Send the list of messages to the queue in batch. var bodyList = Enumerable.Range(1, 10).Select(x => new SimpleObj { Name = $"test sending {x}" }); await queueService.SendBatchAsync(bodyList, "test_routing_key"); ``` -------------------------------- ### Registering BatchQueueSender with RabbitMQCoreClient Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/v7-MIGRATION.md Use this pattern to configure BatchQueueSender after registering RabbitMQCoreClient. Ensure RabbitMQCoreClient is registered first. ```csharp services .AddRabbitMQCoreClient(config.GetSection("RabbitMQ")) .AddBatchQueueSender(); ``` -------------------------------- ### Implement Basic IMessageHandler Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Implement the IMessageHandler interface to process raw message bytes. Configure the handler in RabbitMQCoreClient with specific routing keys. ```csharp public class RawHandler : IMessageHandler { public Task HandleMessage(ReadOnlyMemory message, RabbitMessageEventArgs args, MessageHandlerContext context) { Console.WriteLine(message); return Task.CompletedTask; } } ``` -------------------------------- ### Implement Custom Newtonsoft.Json Serializer Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Create a custom IMessageSerializer and register it via the IRabbitMQCoreClientBuilder to override default serialization behavior. ```csharp using RabbitMQCoreClient.Serializers; using RabbitMQCoreClient.DependencyInjection; using Newtonsoft.Json; // Custom serializer implementation using Newtonsoft.Json public class NewtonsoftJsonMessageSerializer : IMessageSerializer { private readonly JsonSerializerSettings _settings; public NewtonsoftJsonMessageSerializer(Action? configure = null) { _settings = new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore, DateTimeZoneHandling = DateTimeZoneHandling.Utc }; configure?.Invoke(_settings); } public string Serialize(TValue value) { return JsonConvert.SerializeObject(value, _settings); } } // Extension method for fluent registration public static class NewtonsoftBuilderExtensions { public static IRabbitMQCoreClientBuilder AddNewtonsoftJson( this IRabbitMQCoreClientBuilder builder, Action? configure = null) { builder.Serializer = new NewtonsoftJsonMessageSerializer(configure); return builder; } public static IRabbitMQCoreClientConsumerBuilder AddNewtonsoftJson( this IRabbitMQCoreClientConsumerBuilder builder, Action? configure = null) { builder.Builder.AddNewtonsoftJson(configure); return builder; } } // Usage services.AddRabbitMQCoreClient(configuration.GetSection("RabbitMQ")) .AddNewtonsoftJson(settings => { settings.Formatting = Formatting.Indented; settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); ``` -------------------------------- ### Send Messages with IQueueService Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Utilize IQueueService to send objects, raw strings, or byte arrays with optional custom properties and exchange overrides. ```csharp using RabbitMQCoreClient; public class OrderService { private readonly IQueueService _queueService; public OrderService(IQueueService queueService) { _queueService = queueService; } public async Task CreateOrderAsync(Order order) { // Send object - automatically serialized to JSON await _queueService.SendAsync(order, "order.created"); // Send to specific exchange (overrides default) await _queueService.SendAsync(order, "order.created", exchange: "orders_exchange"); // Send raw JSON string await _queueService.SendAsync("""{"orderId": 123, "status": "pending"}""", "order.created"); // Send raw bytes byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes("raw message"); await _queueService.SendAsync(messageBytes, "order.created"); // Send with custom properties (TTL control) var props = QueueService.CreateDefaultProperties(); await _queueService.SendAsync( obj: messageBytes.AsMemory(), props: props, routingKey: "order.created", exchange: "orders_exchange", decreaseTtl: false // Don't decrease TTL on retry ); } } public class Order { public int OrderId { get; set; } public string CustomerName { get; set; } public decimal Total { get; set; } } ``` -------------------------------- ### New RabbitMQ Configuration Format Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Use this format for daily operations. It allows specifying queues, subscriptions, and exchanges. If 'Exchanges' is omitted in 'Queues', the default exchange is used. Queues or Subscriptions can be omitted if no consumers are present. ```json { "HostName": "rabbit-1", "UserName": "user", "Password": "password", "Queues": [ { "Name": "my_queue1", "RoutingKeys": ["primary-event", "hpsm-incident", "hpsm-maintenance"], "DeadLetterExchange": "test_dead_letter" } ], "Subscriptions": [ { "RoutingKeys": [ "event1", "my-messaeg" ], "DeadLetterExchange": "test_dead_letter" } ], "Exchanges": [ { "Name": "test_smon_direct", "IsDefault": true } ] } ``` -------------------------------- ### Register Batch Queue Sender with Configuration Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Registers the batch queue sender using a specific configuration section. ```csharp using RabbitMQCoreClient.DependencyInjection; ... services.AddRabbitMQCoreClient(config.GetSection("RabbitMQ")) .AddBatchQueueSender(configuration.GetSection("QueueFlushSettings")); ``` -------------------------------- ### Old RabbitMQ Configuration Format Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md This older format is still supported and binds the 'Queue' to the 'Exchange'. The default exchange will be used if not explicitly specified. Note the 'UseQuorum' option introduced in v5.1.0. ```json { "HostName": "rabbit-1", "UserName": "user", "Password": "password", "UseQuorum": false, // Introduced in v5.1.0 "Queue": { "QueueName": "my_queue1", "RoutingKeys": ["event1", "my-messaeg"], "DeadLetterExchange": "test_dead_letter" }, "Exchange": { "Name": "direct_exchange" }, "Subscription": { "RoutingKeys": [ "event1", "my-messaeg" ], "DeadLetterExchange": "test_dead_letter" } } ``` -------------------------------- ### Add Custom Serializer Extension Method Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Extension methods to register a custom serializer with the RabbitMQ Core Client builder. Requires Newtonsoft.Json. ```csharp public static class CustomSerializerBuilderExtentions { /// /// Use Custom serializer as default serializer for the RabbitMQ messages. /// public static IRabbitMQCoreClientBuilder AddCustomSerializer(this IRabbitMQCoreClientBuilder builder, Action? setupAction = null) { builder.Serializer = new NewtonsoftJsonMessageSerializer(setupAction); return builder; } /// /// Use Custom serializer as default serializer for the RabbitMQ messages. /// public static IRabbitMQCoreClientConsumerBuilder AddCustomSerializer(this IRabbitMQCoreClientConsumerBuilder builder, Action? setupAction = null) { builder.Builder.AddNewtonsoftJson(setupAction); return builder; } } ``` -------------------------------- ### Monitor RabbitMQ Connection Events in C# Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Implement IHostedService to subscribe to ReconnectedAsync and ConnectionShutdownAsync events for monitoring connection health. ```csharp using RabbitMQCoreClient; using RabbitMQCoreClient.Events; using RabbitMQ.Client.Events; public class ConnectionMonitorService : IHostedService { private readonly IQueueService _queueService; private readonly ILogger _logger; public ConnectionMonitorService(IQueueService queueService, ILogger logger) { _queueService = queueService; _logger = logger; } public Task StartAsync(CancellationToken cancellationToken) { // Subscribe to reconnection events _queueService.ReconnectedAsync += OnReconnected; _queueService.ConnectionShutdownAsync += OnConnectionShutdown; return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _queueService.ReconnectedAsync -= OnReconnected; _queueService.ConnectionShutdownAsync -= OnConnectionShutdown; return Task.CompletedTask; } private Task OnReconnected(object sender, ReconnectEventArgs args) { _logger.LogInformation("RabbitMQ connection restored. Attempt: {Attempt}", args.AttemptNumber); // Re-initialize any state that depends on connection return Task.CompletedTask; } private Task OnConnectionShutdown(object sender, ShutdownEventArgs args) { _logger.LogWarning("RabbitMQ connection lost. Reason: {Reason}", args.ReplyText); // Handle connection loss - e.g., notify monitoring system return Task.CompletedTask; } } ``` -------------------------------- ### Custom Message Serializer Implementation Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Implement the IMessageSerializer interface to create a custom serializer, shown here using Newtonsoft.Json. ```csharp public class CustomMessageSerializer : IMessageSerializer { public Newtonsoft.Json.JsonSerializerSettings Options { get; } static readonly Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver JsonResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver { NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy { ProcessDictionaryKeys = true } }; public CustomMessageSerializer(Action? setupAction = null) { if (setupAction is null) { Options = new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = JsonResolver }; } else { Options = new Newtonsoft.Json.JsonSerializerSettings(); setupAction(Options); } } /// public string Serialize(TValue value) { return Newtonsoft.Json.JsonConvert.SerializeObject(value, Options); } } ``` -------------------------------- ### Configure RabbitMQ Reconnection Settings Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Define reconnection timeout and attempt limits within the RabbitMQ section of appsettings.json. ```json { "RabbitMQ": { "HostName": "rabbit-1", "ReconnectionTimeout": 5000, // 5 seconds between attempts "ReconnectionAttemptsCount": 10, // Max 10 attempts (null = unlimited) "RequestedConnectionTimeout": 30000 // 30 second connection timeout } } ``` -------------------------------- ### Register Batch Queue Sender in DI Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Registers the batch queue sender service in the dependency injection container. ```csharp using RabbitMQCoreClient.DependencyInjection; ... services.AddRabbitMQCoreClient(config.GetSection("RabbitMQ")) .AddBatchQueueSender(); // <- Add buffered batch sending. ``` -------------------------------- ### Default System.Text.Json Serializer Options Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md The default System.Text.Json serializer options include CamelCase for dictionary keys and a JsonStringEnumConverter. ```csharp public static System.Text.Json.JsonSerializerOptions DefaultOptions { get { return new System.Text.Json.JsonSerializerOptions { DictionaryKeyPolicy = System.Text.Json.JsonNamingPolicy.CamelCase, Converters = { new JsonStringEnumConverter() } }; } } ``` -------------------------------- ### Publish Messages from ASP.NET Core Web API Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Integrate RabbitMQ Core Client into ASP.NET Core minimal APIs or controllers to publish messages from HTTP endpoints. Ensure RabbitMQ services are registered and message handlers are configured. ```csharp using RabbitMQCoreClient; using RabbitMQCoreClient.DependencyInjection; var builder = WebApplication.CreateBuilder(args); // Register RabbitMQ services builder.Services .AddRabbitMQCoreClientConsumer(builder.Configuration.GetSection("RabbitMQ")) .AddHandler("order.created", "order.updated") .AddSystemTextJson(opt => opt.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase); var app = builder.Build(); // Minimal API endpoints app.MapPost("/orders", async (CreateOrderRequest request, IQueueService queueService) => { var order = new OrderMessage { OrderId = Random.Shared.Next(1, 10000), CustomerName = request.CustomerName, Total = request.Items.Sum(i => i.Price * i.Quantity), Items = request.Items }; await queueService.SendAsync(order, "order.created"); return Results.Accepted(value: new { order.OrderId, Status = "Processing" }); }); app.MapPost("/orders/bulk", async (List requests, IQueueService queueService) => { var orders = requests.Select(r => new OrderMessage { OrderId = Random.Shared.Next(1, 10000), CustomerName = r.CustomerName, Total = r.Items.Sum(i => i.Price * i.Quantity), Items = r.Items }); await queueService.SendBatchAsync(orders, "order.bulk.created"); return Results.Accepted(); }); app.Run(); public record CreateOrderRequest(string CustomerName, List Items); ``` -------------------------------- ### Custom Exception Routing for Messages Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Customize message routing behavior on exceptions using context.ErrorMessageRouter. Options include moving the message back to the queue or to a dead letter queue. ```csharp internal class Handler : MessageHandlerJson { protected override JsonTypeInfo GetSerializerContext() => SimpleObjContext.Default.SimpleObj; protected override Task HandleMessage(SimpleObj message, RabbitMessageEventArgs args, MessageHandlerContext context) { try { ProcessMessage(message); } catch (ArgumentException e) when (e.Message == "parser failed") { context.ErrorMessageRouter.MoveToDeadLetter(); throw; } catch (Exception) { context.ErrorMessageRouter.MoveBackToQueue(); throw; } return Task.CompletedTask; } void ProcessMessage(SimpleObj obj) { if (obj.Name != "my test name") throw new ArgumentException("parser failed"); Console.WriteLine("It's all ok."); } } ``` -------------------------------- ### Custom JSON Serialization Context for MessageHandlerJson Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/v7-MIGRATION.md Implement a custom JsonSerializerContext and override GetSerializerContext to provide JSON serialization context for MessageHandlerJson. ```csharp public class SimpleObj { public required string Name { get; set; } } [JsonSerializable(typeof(SimpleObj))] public partial class SimpleObjContext : JsonSerializerContext { } public class Handler : MessageHandlerJson { protected override JsonTypeInfo GetSerializerContext() => SimpleObjContext.Default.SimpleObj; protected override Task HandleMessage(SimpleObj message, RabbitMessageEventArgs args) { return Task.CompletedTask; } } ``` -------------------------------- ### SendAsync Generic Method Signature Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md This generic method is used for publishing class objects as messages, utilizing the configured serializer. ```csharp public static ValueTask SendAsync( this IQueueService service, T obj, string routingKey, string? exchange = default, CancellationToken cancellationToken = default ) where T : class ``` -------------------------------- ### Implement JSON Message Handler Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Use MessageHandlerJson for JSON-serialized messages. Provide a source-generated JsonSerializerContext for deserialization. Override OnParseError for custom error handling during deserialization. ```csharp internal sealed class SimpleObjectHandler : MessageHandlerJson { readonly ILogger _logger; public SimpleObjectHandler(ILogger logger) { _logger = logger; } protected override JsonTypeInfo GetSerializerContext() => SimpleObjContext.Default.SimpleObj; protected override Task HandleMessage(SimpleObj message, RabbitMessageEventArgs args, MessageHandlerContext context) { _logger.LogInformation("Incoming simple object name: {Name}", message.Name); return Task.CompletedTask; } protected override ValueTask OnParseError(string json, Exception e, RabbitMessageEventArgs args, MessageHandlerContext context) { _logger.LogError(e, "Incoming message can't be deserialized. Error: {ErrorMessage}", e.Message); return base.OnParseError(json, e, args, context); } } public class SimpleObj { public required string Name { get; set; } } [JsonSerializable(typeof(SimpleObj))] public partial class SimpleObjContext : JsonSerializerContext { } ``` -------------------------------- ### Register Custom EventsWriter Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Registers a custom implementation of IEventsWriter in the DI container. ```csharp builder.Services.AddTransient(); ``` -------------------------------- ### Handle Custom EventItem Types Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Casting logic within WriteBatch to handle custom EventItemWithSourceObject types. ```csharp public async Task WriteBatch(IEnumerable events, string routingKey) { ... foreach (EventItem item in events) { if (item is EventItemWithSourceObject eventWithSource) { // Working с item.Source } } ... } ``` -------------------------------- ### Register Custom IEventsHandler Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/README.md Registers a custom implementation of IEventsHandler for event hooks. ```csharp builder.Services.AddTransient(); ``` -------------------------------- ### Implement Typed JSON Message Handler in C# Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Inherit from MessageHandlerJson to process typed messages. Ensure a source-generated JsonSerializerContext is provided via GetSerializerContext for AOT support. ```csharp using RabbitMQCoreClient; using RabbitMQCoreClient.Models; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; public class OrderMessageHandler : MessageHandlerJson { private readonly ILogger _logger; private readonly IOrderRepository _orderRepository; public OrderMessageHandler( ILogger logger, IOrderRepository orderRepository) { _logger = logger; _orderRepository = orderRepository; } // Required: Provide source-generated JsonTypeInfo for AOT compatibility protected override JsonTypeInfo GetSerializerContext() => OrderMessageContext.Default.OrderMessage; protected override async Task HandleMessage( OrderMessage message, RabbitMessageEventArgs args, MessageHandlerContext context) { _logger.LogInformation("Processing order {OrderId} for {Customer}", message.OrderId, message.CustomerName); // Access raw JSON if needed _logger.LogDebug("Raw JSON: {Json}", RawJson); await _orderRepository.SaveAsync(message); } protected override ValueTask OnParseError( string json, Exception e, RabbitMessageEventArgs args, MessageHandlerContext context) { _logger.LogError(e, "Failed to parse order message: {Json}", json); // Move to dead letter queue on parse error context.ErrorMessageRouter.MoveToDeadLetter(); return default; } } public class OrderMessage { public int OrderId { get; set; } public required string CustomerName { get; set; } public decimal Total { get; set; } public List Items { get; set; } = new(); } public class OrderItem { public string ProductId { get; set; } public int Quantity { get; set; } public decimal Price { get; set; } } // Source-generated JSON serialization context (required for AOT) [JsonSerializable(typeof(OrderMessage))] [JsonSerializable(typeof(List))] public partial class OrderMessageContext : JsonSerializerContext { } // Registration with multiple routing keys and retry key services.AddRabbitMQCoreClientConsumer(configuration.GetSection("RabbitMQ")) .AddHandler( routingKeys: new[] { "order.created", "order.updated" }, options: new ConsumerHandlerOptions { RetryKey = "order.retry" }); ``` -------------------------------- ### Updated IMessageHandler HandleMessage Signature Source: https://github.com/monqdl/rabbitmqcoreclient/blob/master/v7-MIGRATION.md The HandleMessage method now includes a MessageHandlerContext argument. Remove old properties like ErrorMessageRouter and Options from your implementation. ```csharp Task HandleMessage(ReadOnlyMemory message, RabbitMessageEventArgs args, MessageHandlerContext context); ``` -------------------------------- ### Handle Message Exceptions with ErrorMessageRouting Source: https://context7.com/monqdl/rabbitmqcoreclient/llms.txt Use the ErrorMessageRouter within a MessageHandlerJson to explicitly route messages to dead letter queues or back to the queue upon specific exceptions. ```csharp using RabbitMQCoreClient; using RabbitMQCoreClient.Models; using System.Text.Json.Serialization.Metadata; public class PaymentHandler : MessageHandlerJson { private readonly IPaymentService _paymentService; private readonly ILogger _logger; public PaymentHandler(IPaymentService paymentService, ILogger logger) { _paymentService = paymentService; _logger = logger; } protected override JsonTypeInfo GetSerializerContext() => PaymentContext.Default.PaymentRequest; protected override async Task HandleMessage( PaymentRequest message, RabbitMessageEventArgs args, MessageHandlerContext context) { try { await _paymentService.ProcessPaymentAsync(message); } catch (InvalidPaymentDataException ex) { // Permanent error - move to dead letter queue immediately _logger.LogError(ex, "Invalid payment data for {PaymentId}", message.PaymentId); context.ErrorMessageRouter.MoveToDeadLetter(); throw; } catch (PaymentGatewayTimeoutException ex) { // Transient error - retry by sending back to queue with TTL decrease _logger.LogWarning(ex, "Gateway timeout for {PaymentId}, will retry", message.PaymentId); context.ErrorMessageRouter.MoveBackToQueue(decreaseTtl: true); throw; } catch (PaymentGatewayOverloadedException ex) { // Transient error - retry without decreasing TTL _logger.LogWarning(ex, "Gateway overloaded for {PaymentId}, will retry", message.PaymentId); context.ErrorMessageRouter.MoveBackToQueue(decreaseTtl: false); throw; } catch (Exception ex) { // Default behavior: message goes back to queue with TTL decreased // After TTL reaches 0, message goes to dead letter queue _logger.LogError(ex, "Unexpected error processing {PaymentId}", message.PaymentId); throw; } } } public class PaymentRequest { public string PaymentId { get; set; } public decimal Amount { get; set; } public string Currency { get; set; } } [JsonSerializable(typeof(PaymentRequest))] public partial class PaymentContext : JsonSerializerContext { } public class InvalidPaymentDataException : Exception { } public class PaymentGatewayTimeoutException : Exception { } public class PaymentGatewayOverloadedException : Exception { } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.