RabbitMQ Consumer always directly shutsdown (C#)

ぐ巨炮叔叔 提交于 2020-01-13 13:54:29

问题


At The moment im learning how to work with the RabbitMQ. Sending works. But Recieving doesn't work. This is my code:

    var factory = new ConnectionFactory() { HostName = hostName };
        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 += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine("Recieved: {0}", message);
            };
            consumer.Shutdown += (o, e) =>
            {
                Console.WriteLine("Error with RabbitMQ: {0}", e.Cause);
                createConnection(hostName, queueName);
            };
            channel.BasicConsume(queueName, true, consumer);
        }

This is copied from the Tutorial. If I start the Application, consumer.Shutdown is directly called and I get:

    {AMQP close-reason, initiated by Application, code=200, text="Goodbye", classId=0, methodId=0, cause=}

Can anyone help me?


回答1:


channel.BasicConsume is non-blocking call, which means it will return immediately. What happens next in your example is your channel and connection are getting disposed (because of using statement), and so you see immediate shutdown. In the example you copied this code from, there is Console.ReadLine statement right after channel.BasicConsume. This prevents channel and connection from disposing until user press key in console.



来源:https://stackoverflow.com/questions/42054079/rabbitmq-consumer-always-directly-shutsdown-c

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