azureservicesubscriptionrebusbus

Multiple Subscribers to same message Rebus Azure Service Bus


I have two exactly same consumers

Consumer 1

using (var adapter = new BuiltinHandlerActivator())
        {
            adapter.Handle<string>(async (bus, message) =>
            {
                Console.WriteLine("Got message > " + message);

                await bus.Reply("Received in consumer 1");
            });

            Configure.With(adapter)
                .Transport(t => t.UseAzureServiceBus(connectionString, "server"))
                .Start();

            adapter.Bus.Subscribe<string>().Wait();

            Console.WriteLine("Press ENTER to quit");
            Console.ReadLine();
        }

Consumer 2

using (var adapter = new BuiltinHandlerActivator())
        {
            adapter.Handle<string>(async (bus, message) =>
            {
                Console.WriteLine("Got message > " + message);

                await bus.Reply("Received in Consumer 2");
            });

            Configure.With(adapter)
                .Transport(t => t.UseAzureServiceBus(connectionString, "server"))
                .Start();

            adapter.Bus.Subscribe<string>().Wait();

            Console.WriteLine("Press ENTER to quit");
            Console.ReadLine();
        }

Producer

using (var adapter = new BuiltinHandlerActivator())
        {
            adapter.Handle<string>(async message =>
            {
                Console.WriteLine("Returned > " + message);
            });

            var bus = Configure
                .With(adapter)
                .Transport(t => t.UseAzureServiceBus(connectionString, "client"))
                .Routing(r => r.TypeBased().Map<string>("server"))
                .Start();

            Console.WriteLine("Press Q to quit or any other key to produce a job");
            while (true)
            {
                Console.Write("Write something > ");
                var text = Console.ReadLine();

                if (string.IsNullOrWhiteSpace(text)) break;

                bus.Publish(text).Wait();
            }
        }

What I expect is whenever I send message from the Producer, both my Consumers to display the message. Now it only does it in one of them. When I close that one and send another message, the remaining one receives it.


Solution

  • Basically, you only need to give the consumers different names. Rebus creates a topic for each producer (based on assembly, namespace, type), and creates subscriptions for each consumer in these topics. If two consumers use the same name, they compete for the message.

                    .Transport(t => t.UseAzureServiceBus(connectionString, "consumer1"))
                    .Transport(t => t.UseAzureServiceBus(connectionString, "consumer2"))
    

    Full example: https://github.com/rebus-org/RebusSamples/tree/master/PubSubNative

    Some other helpful links: