Home .NET .NET Core + RabbitMQ

.NET Core + RabbitMQ

by admin

When developing microservices, the question arises of providing information from one service to other services as events occur.In this case, it is important to have a system without sender-recipient binding.In this case, the Publisher-Subscriber patternis used.
There are many messaging products on the market that support the Publisher-Subscriber pattern, such as Azure Service Bus, RabbitMQor Apache Kafka.
Recently I published two NuGetlibraries for quick and easy configuration of event-based communication using the Azure Service Bus and RabbitMQ.This short how-to article describes the steps for using the latter.

Source

Publisher is a .NET Core application that acts as a sender.
Subscriber – A .NET Core application that acts as a sender.

How-To

1.In publisher and subscriber applications set two NuGet libraries.

PM> Install-Package Autofac.Extensions.DependencyInjectionPM> Install-Package EventBus.RabbitMQ.Standard

2.In publisher and subscriber applications add the configuration to the appsettings.json

{"RabbitMq": {"BrokerName": "test_broker", "AutofacScopeName": "test_autofac", "QueueName": "test_queue", "RetryCount": "5", "VirtualHost": "your_virtual_host", "Username": "your_username", "Password": "your_password", "Host": "your_host", "DispatchConsumersAsync": true}}

These settings can be obtained at CoudAMQP Alternatively, you can use RabbitMQ locally ( Docker image ).
3. In publisher and subscriber applications, create a class for the event that will be published and, later on, handled.

public class ItemCreatedIntegrationEvent: IntegrationEvent{public string Title { get; set; }public string Description { get; set; }public ItemCreatedIntegrationEvent(string title, string description){Title = title;Description = description;}}

4. In subscriber application, create a class for the event handler ItemCreatedIntegrationEvent

public class ItemCreatedIntegrationEventHandler : IIntegrationEventHandler<ItemCreatedIntegrationEvent>{public ItemCreatedIntegrationEventHandler(){}public async Task Handle(ItemCreatedIntegrationEvent @event){//Handle the ItemCreatedIntegrationEvent event here.}}

5. In publisher and subscriber applications update Program.cs by adding one line.

public class Program{public static void Main(string[] args){CreateHostBuilder(args).Build().Run();}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory()) //Add this line..ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup> ();});}

6. In publisher application update the method ConfigureServices in Startup.cs

public class Startup{public void ConfigureServices(IServiceCollection services){...var rabbitMqOptions = Configuration.GetSection("RabbitMq").Get<RabbitMqOptions> ();services.AddRabbitMqConnection(rabbitMqOptions);services.AddRabbitMqRegistration(rabbitMqOptions);...}}

7. In subscriber application, create an extension EventBusExtension

public static class EventBusExtension{public static IEnumerable<IIntegrationEventHandler> GetHandlers(){return new List<IIntegrationEventHandler>{new ItemCreatedIntegrationEventHandler()};}public static IApplicationBuilder SubscribeToEvents(this IApplicationBuilder app){var eventBus = app.ApplicationServices.GetRequiredService<IEventBus> ();eventBus.Subscribe<ItemCreatedIntegrationEvent, ItemCreatedIntegrationEventHandler> ();return app;}}

8. In subscriber application update the methods ConfigureServices and Configure in Startup.cs

public class Startup{public void ConfigureServices(IServiceCollection services){...var rabbitMqOptions = Configuration.GetSection("RabbitMq").Get<RabbitMqOptions> ();services.AddRabbitMqConnection(rabbitMqOptions);services.AddRabbitMqRegistration(rabbitMqOptions);services.AddEventBusHandling(EventBusExtension.GetHandlers());...}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){...app.UseAuthorization();...}}

9. For demonstration and simplicity, you can create a controller in publisher application with a method in which the event is published.

public class ItemController : ControllerBase{private readonly IEventBus _eventBus;public ItemController(IEventBus eventBus){_eventBus = eventBus;}[HttpPost]public IActionResult Publish(){var message = new ItemCreatedIntegrationEvent("Item title", "Item description");_eventBus.Publish(message);return Ok();}}

10. Now you can publish the ItemCreatedIntegrationEvent. Run both applications, call the POST method Publish in subscriber and process the event in the subscriber

Links

You may also like