Subscribing to messages

In order to send or receive messages, we have to be subscribed to our underlying messaging system. You will notice that, to do this, we call the Subscribe method. You'll also notice that this is another one of those sections that gets repeated a lot, for the same reasons as stated previously. But this is also one of the great candidates to be put into our base class for everyone to use. At the time of writing, it was not included in the base class source code, but I would take a look anyway, I might have been able to sneak in a few goodies between draft and final!

The following code does the following:

  • Creates our connection to the RabbitMQ server
  • Enables message versioning
  • Declares our exchanges
  • Declares our email queue
  • Binds our queue to the exchange
  • Subscribes to our EmailSendRequest message and provides the function to call once the message is received

Here is our subscribe function which will handle declaring and binding Exchanges and Queues, as well as subscribing to messages:

public void Subscribe()
{
Bus = RabbitHutch.CreateBus("host=localhost",
x =>
{
x.Register<IConventions, AttributeBasedConventions>();
x.EnableMessageVersioning();
});
IExchange exchange = Bus.Advanced.ExchangeDeclare("EvolvedAI", ExchangeType.Topic);
IQueue queue = Bus.Advanced.QueueDeclare("Email");
Bus.Advanced.Bind(exchange, queue, Environment.MachineName);
Bus.Subscribe<EmailSendRequest>(Environment.MachineName, msg => { ProcessEmailSendRequestMessage(msg); },
config => config?.WithTopic("Email"));
}

The preceding highlighted lines are the code that is specific to us. More concretely, the highlighted code subscribes to, and processes, EmailSendReceipt messages for us. These few lines of code are where all the magic happens.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset