Consumer "received" event not firing - c#

I'm trying to set up a subscription to a RabbitMQ queue and pass it a custom event handler.
So I have a class called RabbitMQClient which contains the following method:
public void Subscribe(string queueName, EventHandler<BasicDeliverEventArgs> receivedHandler)
{
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(
queue: queueName,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null
);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += receivedHandler;
channel.BasicConsume(
queue: queueName,
autoAck: false,
consumer: consumer
);
}
}
}
I'm using dependency injection, so I have a RabbitMQClient (singleton) interface for it.
In my consuming class, I have this method which I want to act as the EventHandler
public void Consumer_Received(object sender, BasicDeliverEventArgs e)
{
var message = e.Body.FromByteArray<ProgressQueueMessage>();
}
And I'm trying to subscribe to the queue like this:
rabbitMQClient.Subscribe(Consts.RabbitMQ.ProgressQueue, Consumer_Received);
I can see that the queue starts to get messages, but the Consumer_Received method is not firing.
What am I missing here?

"Using" calls dispose on your connection and your event wont be triggered. Just remove your "using" block from the code so that it doesn't close the connection.
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
channel.QueueDeclare(
queue: queueName,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += receivedHandler;
channel.BasicConsume(
queue: queueName,
autoAck: false,
consumer: consumer);

Related

RabbitMQ: Fast processing of time consuming events

I'm experimenting with RabbitMQ and I hope someone can give me some hints.
I try to do the following: Processing events, which are time consuming to process, as quickly as possible with one consumer.
The test: 5 events and each one takes 2 seconds to process.
First attempt: 'Hello world' example from RabbitMQ (https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html).
static void Main(string[] args)
{
// Sender
var factory = new ConnectionFactory { HostName = "localhost"};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
const string message = "Hello World!";
for (int i = 1; i <= 5; i++)
{
var body = Encoding.UTF8.GetBytes($"{message} {i}");
channel.BasicPublish(exchange: string.Empty,
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine($"Sent {message} {i}");
}
// Consumer
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Thread.Sleep(2000);
Console.WriteLine($"Received {message}");
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine("Press [enter] to exit.");
Console.ReadLine();
}
Conclusion: Too slow because events are processed synchronously.
Second attempt: Asynchronous processing using AsyncEventingBasicConsumer.
Code changes:
DispatchConsumersAsync-property is set in the ConnectionFactory
AsyncEventingBasicConsumer is used
consumer.Received is async
static void Main(string[] args)
{
// Sender
var factory = new ConnectionFactory { HostName = "localhost", DispatchConsumersAsync = true };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
const string message = "Hello World!";
for (int i = 1; i <= 5; i++)
{
var body = Encoding.UTF8.GetBytes($"{message} {i}");
channel.BasicPublish(exchange: string.Empty,
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine($"Sent {message} {i}");
}
// Consumer
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
await Task.Delay(2000);
Console.WriteLine($"Received {message}");
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine("Press [enter] to exit.");
Console.ReadLine();
}
Conclusion: Too slow because events are still processed synchronously.
Third attempt: Async event handler for the consumer.
Code changes:
DispatchConsumersAsync-property is removed in the ConnectionFactory.
EventingBasicConsumer is used again
static void Main(string[] args)
{
// Sender
var factory = new ConnectionFactory { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
const string message = "Hello World!";
for (int i = 1; i <= 101; i++)
{
var body = Encoding.UTF8.GetBytes($"{message} {i}");
channel.BasicPublish(exchange: string.Empty,
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine($"Sent {message} {i}");
}
// Consumer
var consumer = new EventingBasicConsumer(channel);
consumer.Received += async (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
await Task.Delay(2000);
Console.WriteLine($"Received {message}");
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine("Press [enter] to exit.");
Console.ReadLine();
}
Conclusion: This is the result I want. The messages are processed very fast even when 1000 events are published.
But is this a proper solution for usage in a production environment?
I hope someone can help to clarify this or share their experience for processing events fast in a production environment.

C#, RabbitMq How can I send back the processed message

I just started learning RabbitMQ yesterday and I don't understand how it can be implemented.
Here is my producer
public class RabbitMQProducerService: IMessageSender
{
public void SendMessage<T>(T message)
{
var factory = new ConnectionFactory { HostName = "localhost" };
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
channel.QueueDeclare("Input", exclusive: false);
var json = JsonConvert.SerializeObject(message);
var body = Encoding.UTF8.GetBytes(json);
channel.BasicPublish(exchange: "", routingKey: "Input", basicProperties: null, body: body);
}
}
And my subscriber
string exepction = "";
StatisticOfTest statistic;
var factory = new ConnectionFactory
{
HostName = "localhost"
};
var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare("Input", exclusive: false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, eventArgs) =>
{
SolutionService solution = new SolutionService();
var body = eventArgs.Body.ToArray();
var jsonStr = Encoding.UTF8.GetString(body);
SolutionAddModel solutionAdd = JsonConvert.DeserializeObject<SolutionAddModel>(jsonStr);
if (String.IsNullOrEmpty(solution.Validating(solutionAdd)))
{
statistic = solution.Create(solutionAdd); //I want to return statistic
}
else
{
exepction = solution.Validating(solutionAdd); // Or Exception
}
Console.WriteLine($"Message received: {jsonStr}");
};
channel.BasicConsume(queue: "Input", autoAck: true, consumer: consumer);
Console.ReadKey();
Based on the result, I want to return statistic or exception. But to another queue, for example, to some Output queue
consumer.Received += (model, eventArgs) => { ... }
The ... is the place when you declare what will happen, when a new message is received. The code there would be an event handler for a Received event.
In your case you want each new message to be published to a queue on some condition. Easy to do, just publish a message in your event handler code:
...
// Create a separate channel for sending messages to the output queue
var outputChannel = connection.CreateModel();
// Declare the output queue, you want to send messages to
outputChannel.QueueDeclare("Output", exclusive: false);
// Specify how the actual processing is going to happen
consumer.Received += (model, eventArgs) =>
{
var body = GetMessageBody(eventArgs.Body); // This is where you get new message content based on the received message.
outputChannel.BasicPublish(exchange: "", routingKey: "Input", basicProperties: null, body: body);
};
...
Also, looking at your producer code: you don't need to create a new connection, a new channel, and declare a queue every time you want to send a message. You could do it beforehand just once. It would really save RabbitMQ's resources.
RabbitMQ also has a connection limit, so sometime in the future your program would stop working. It is better if an application actually uses a single connection for everything, if possible, just spawning channels where needed.
Also, don;t forget, that IConnection and IModel are implementing IDisposable, so you should dispose of them properly.
This is how you should do it:
// 'using' tells the compiler to generate a Dispose call for this object at the end of the current block.
using var connection = connectionFactory.CreateConnection();
uisng var channel = connection.CreateModel();
channel.QueueDeclare("Input", exclusive: false);
for (var i = 0; i < 100l i++)
producer.SendMessage(i);

Unit test running forever for call back method in C#

Following is the method to receive the message on RabbitMq Queue. Method works fine but the unit testing this method has problem mentioned below
public void GetMessage(Action<string> action)
{
//create a connection factory
var factory = new ConnectionFactory();
if (_connectionString != null)
{
//assign connection string of rabbitmq
factory.Uri = new Uri(_connectionString);
}
//create connection and channel from connectionfactory
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
//declare the queque on the channel
channel.QueueDeclare(queue: _queque,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
//create consumer using the channel
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
//When message is recieved on the consumer this will be triggered
var body = ea.Body.ToArray();
_message = Encoding.UTF8.GetString(body);
//call the method passed by the caller method
action(_message);
};
//add the consumer on this channel
channel.BasicConsume(queue: _queque,
autoAck: true,
consumer: consumer);
Console.ReadLine();
}
}
How to write a unit test test above message. Below unit test loading forever inside the call back method and the execution never goes to Assert.Equal line.
[Fact]
public async Task AddMessageAsync_ShouldAddToQueue()
{
//Arrange
string messageToSend = "Test";
string recievedMessage = null;
var queue = GetQueueManager();
queue.Message = messageToSend;
await queue.AddMessageAsync();
//Act
queue.GetMessage((string message) =>
{
//Hit here and recieved the message but does not exist from this method
recievedMessage = message;
});
//Assert
Assert.Equal(messageToSend, recievedMessage);
}
One way to adress the issue would be a synchronization barrier.
Here is an example: (There may be more efficient ways, though.)
... // Your code with some changes:
//create connection and channel from connectionfactory
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
//declare the queque on the channel
channel.QueueDeclare(queue: _queque,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
// Set up a synchronization barrier.
using (var barrier = new ManualResetEventSlim(false))
{
//create consumer using the channel
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
//When message is recieved on the consumer this will be triggered
var body = ea.Body.ToArray();
_message = Encoding.UTF8.GetString(body);
try // you don't want "injected" code to break yours.
{
//call the method passed by the caller method
action(_message);
}
catch(Exception)
{
// at least log it!
}
finally
{
barrier.Set(); // Signal Event fired.
}
};
//add the consumer on this channel
channel.BasicConsume(queue: _queque,
autoAck: true,
consumer: consumer);
barrier.Wait(); // Wait for Event to fire.
}
}
I would imagine that the RabbitMQ API has had an update to support async/await instead of event-based? If so, then using that would of course be preferable.
If not: You may also want to explore Tasks and the Event-based Asynchronous Pattern (EAP)

How do I get RabbitMQ to read from the queue one by one?

I am just playing with RabbitMQ and trying to get a test sender and receiver set up in two C# projects.
TestSender.cs
using System;
using RabbitMQ.Client;
using System.Text;
public class TestSender
{
public TestSender()
{
}
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "Test Queue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
Console.WriteLine(" Press [S] to send a message, [Enter] to exit.");
ConsoleKey key;
int messageId = 0;
while (true)
{
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Enter)
break;
if (key == ConsoleKey.S)
{
string message = "Message " + (++messageId).ToString();
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine("Sent {0}", message);
}
}
}
}
}
}
TestReceiver.cs
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
public class TestReceiver
{
public TestReceiver()
{
}
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
// Declare the queue here because we might start the consumer before the publisher
// so the queue should exist before we try to consume messages from it.
channel.QueueDeclare(queue: "Test Queue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
Console.WriteLine(" Press [R] to receive a message, [Enter] to exit.");
// Register a consumer to listen to a specific queue.
channel.BasicConsume(queue: "Test Queue",
autoAck: true,
consumer: consumer);
ConsoleKey key;
while (true)
{
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Enter)
break;
if (key == ConsoleKey.R)
{
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("Received {0}", message);
};
}
}
}
}
}
}
I set it up in such a way that if you press the S key, it sends a message to the queue and if you press the R key, it reads from the queue. The sending works but the receiving does absolutely nothing. I removed the while loop and keypress code and the receiving works. However, I would like to figure out how to get messages consumed one by one and not all at once. In addition, does anyone know if RabbitMQ can persist messages in the queue or do they have to be dequeued when consumed?
RabbitMQ sends a new message to consumer/subscriber when you Acknowledge the current message. RabbitMQ will persist message in the queue(durable mode only) until not acknowledged.
Remove autoAck: true options from channel.BasicConsume function. use channel.BasicAck function to ack a message when R key pressed.

RabbitMQ Can't Send and Receive from same process

I'm working through my first steps with RabbitMQ and have a question on why this didn't work.
The basic tutorial (https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html) has one executable to send to the broker and another to receive it.
I ran this code through a single console app in Visual Studio and couldn't receive any messages.
If I take the "Receive" code and put it into a separate console app and open that, I get the message (no other code changes).
Can someone explain why I'm not able to have both in the same process? I had figured that the connection factory would handle independent connections accordingly regardless of whether it was the same process or not.
For the sake of completeness (though I doubt it's required), here's the code that didn't work until I pulled out the "Receiver" code and put it into it's own console app:
class Program
{
static void Main(string[] args) {
Receiver.Receive();
Console.WriteLine("receiver set up");
System.Threading.Thread.Sleep(5000);
Console.WriteLine("sending...");
Test.Send();
// can also reverse order of send/receive methods, same result
Console.ReadKey();
}
}
public class Receiver
{
public static void Receive() {
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection()) {
using (var channel = connection.CreateModel()) {
channel.QueueDeclare("hello", false, false, false, null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) => {
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
System.Diagnostics.Debug.WriteLine("=====================");
System.Diagnostics.Debug.WriteLine(message);
System.Diagnostics.Debug.WriteLine("=====================");
};
channel.BasicConsume("hello", true, consumer);
}
}
}
}
public class Test
{
public static void Send() {
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection()) {
using (var channel = connection.CreateModel()) {
channel.QueueDeclare("hello", false, false, false, null);
string message = "Check it!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "hello", null, body);
}
}
}
}
I think code has a problem. When you send message then Receive connection and channel already dead (Dispose called).
Standard code from RabbitMQ site:
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
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);
Console.WriteLine(" [x] Received {0}", message);
};
channel.BasicConsume(queue: "hello",
noAck: true,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
connection and channel are yet alive when client received message.

Categories