Mass Transit with RabbitMQ Hello World

Full source code is available here.

Below is an example of how to use RabbitMQ with Mass Transit service bus.

See here for instructions on how to install Rabbit MQ.

Mass Transit is installed via nuget, its current version is 2.9.9. You also need to add the RabbitMQ.Client, but stick with version 3.4.0 or less, there was a breaking change in subsequent versions that Mass Transit has not caught up with.

In simple terms Mass Transits lets you send messages from a producer to a consumer/worker. I’m not going into any more detail, there is documentation available elsewhere.

The Code

In the sender create a bus instance and connect it to RabbitMQ –

            var bus = ServiceBusFactory.New(cfg =>
            {
                cfg.UseRabbitMq();
                cfg.ReceiveFrom("rabbitmq://localhost/nodogmablog_queue_sender");
            });

Connect the worker to the bus –

            Bus.Initialize(sbc =>
            {
                cfg.UseRabbitMq();
                cfg.ReceiveFrom("rabbitmq://localhost/nodogmablog_queue_worker");

                cfg.Subscribe(subs => subs.Consumer<SimpleMessageConsumer>().Permanent());
            });

Send the message to the bus –

                var simpleMessage = new SimpleMessage() { Body = messageText };
                bus.Publish<SimpleMessage>(simpleMessage, pubContext =>
                {
                    //pubContext.SetHeader("Header1", "some value");
                    pubContext.SetDeliveryMode(DeliveryMode.Persistent);
                });

And finally the consume the message –

    public class SimpleMessageConsumer : Consumes<SimpleMessage>.Context
    {
        public void Consume(IConsumeContext<SimpleMessage> incomingMessage)
        {
            Console.WriteLine(incomingMessage.Message.Body);
        }
    }

You have to set SimpleMassTransitRabbitMQHelloWorld.Sender and SimpleMassTransitRabbitMQHelloWorld.Worker as start up projects by right clicking the solution and opening properties.

SetStartupProjects

That’s the basics of it, the full source code is available here.

Leave a Reply

Your email address will not be published. Required fields are marked *