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?
The problem with your first piece of code is that your program finishes execution before it can handle any messages. EventingBasedConsumer is asynchronous and won't actually prevent you program from exiting. You need to implement a wait of some sort to be able to actually handle messages. Try adding Thread.Sleep(10000); just after Channel.BasicConsume and check if there are any messages being processed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With