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 -

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

Connect the worker to the bus -

1            Bus.Initialize(sbc =>
2            {
3                cfg.UseRabbitMq();
4                cfg.ReceiveFrom("rabbitmq://localhost/nodogmablog_queue_worker");
5
6                cfg.Subscribe(subs => subs.Consumer<SimpleMessageConsumer>().Permanent());
7            });

Send the message to the bus -

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

And finally the consume the message -

1    public class SimpleMessageConsumer : Consumes<SimpleMessage>.Context
2    {
3        public void Consume(IConsumeContext<SimpleMessage> incomingMessage)
4        {
5            Console.WriteLine(incomingMessage.Message.Body);
6        }
7    }

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.

comments powered by Disqus

Related