问题
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?
回答1:
"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);
来源:https://stackoverflow.com/questions/52159857/consumer-received-event-not-firing