Consumer “received” event not firing

白昼怎懂夜的黑 提交于 2021-02-08 14:28:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!