Search code examples
c#.net.net-corerabbitmqmicroservices

One event multiple consumers (only one consumer working) Rabbitmq


MyProject.Core
MyProject.Services.DataImporter
Myproject.Services.Cars
Myproject.Services.Cars2

Both DataImporter and Cars projects are referencing MyProject.Core project. I have an event (DataImportFinishedEvent) that is emitted by the DataImporter service. Both Services.Cars and Services.Cars2 are subscribed to this event.

When the event is fired I am able to fetch this event in Services.Cars and after I process the event I cannot fetch it in Services.Cars2. If I disable Services.Cars then I'm able to fetch the event on Services.Cars2 successfully.

In short, I cannot have multiple subscribers for one event, as soon as the event is processed it's like no longer exists for other consumers.

Not sure what code should I share but here how's my event and event handler looks like.

public class DataImportFinishedEvent: Event
{
   public string Data { get; set; }
}

public class DataImportFinishedEventHandler : IEventHandler<DataImportFinishedEvent> {
   public Task Handle(DataImportFinishedEvent @event)
   {
        return Task.FromResult(true);
   }
}

In case you need more info I'm injecting RabbitMQBus implementation in both services (.net core)

 services.AddSingleton<IEventBus, RabbitMQBus>(sp =>
 {
      var scopeFactory = sp.GetRequiredService<IServiceScopeFactory>();
      return new RabbitMQBus(sp.GetService<IMediator>(), scopeFactory);
 });

Please let me know if you need more info from the RabbitMQBus implementation.


Solution

  • When you upload a message in a queue in RabbitMQ that message will be consumed only once.

    In order to achive the same message to be consumed by several consumers you have to use a fan-out exchange. In the link attached you can find a very descriptive post of how this concept works.

    What is happening in the background is that when you uploada message in the exchange, your message is placed in several queues. And then each service can consume it's own message.