RabbitMQ C# Practical Example

Viewed 7741

I am new to RabbitMQ and am having trouble finding a VS2017 C# example that does more that prints to the Console. I can send and receive messages no problem, but I would like to take the contents of the message and actually use it. Below is the code I have:

using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.IO;

namespace MyCode
{
  class Program
  {
    public static void Main()
    {
      var factory = new ConnectionFactory() { HostName = "xxx.xx.x.x", UserName = "MyTest", Password = "MyTest", Port = 5672 };
      using (var connection = factory.CreateConnection())
      {
        using (var channel = connection.CreateModel())
        {

          channel.QueueDeclare(queue: "MyTest", durable: false, exclusive: false, autoDelete: false, arguments: null);

          var consumer = new EventingBasicConsumer(channel);
          consumer.Received += (model, ea) =>
          {
            var body = ea.Body;
            var message = Encoding.UTF8.GetString(body);
            DoSomething(message);
          };

          channel.BasicConsume(queue: "MyTest", autoAck: true, consumer: consumer);
        }
      }
    }
    static void DoSomething(string message)
    {
      File.AppendAllText(@"C:\RMQ.txt", message);
    }
  }
}

The problem is, I can't ever seem to get anything out of the Consumer.Received step. Any help would be much appreciated!

EDIT::

I was able to make it work by using this code instead:

  var factory = new ConnectionFactory() { HostName = "xxx.xx.x.x", UserName = "MyTest", Password = "MyTest", Port = 5672 };
  using (IConnection connection = factory.CreateConnection())
  {
    using (IModel channel = connection.CreateModel())
    {

      channel.QueueDeclare(queue: "MyTest", durable: false, exclusive: false, autoDelete: false, arguments: null);

      BasicGetResult consumer = channel.BasicGet("MyTest", true);

      if (consumer != null)
      {
        string message = Encoding.UTF8.GetString(consumer.Body);
        DoSomething(message);
      }

    }
  }

Anybody see any issues with this?

2 Answers

For fire and forget applications, that tries to setup the read, try not to use the "using" statement for your connection and channel. They will go out of scope (set for garbage collection) once the the subroutine finish the execution.

Obviously, you need to have the console application up and running to receive the message. So, I did put a Console.Readline() in the calling app to prevent the thread from exiting.

Related