使用 MQ 发送消息失败

Failed to send message using MQ

在我的服务器端,我使用 docker 部署了 RabbitMq 消息中间件,它运行良好。但是我把它和asp.net核心结合起来,它不能成功发送消息。

包:https://www.nuget.org/packages/RabbitMQ.Client/

我得到了一些答案:

RabbitMQ adopts the message response mechanism, that is, after the consumer receives a message, it needs to send a response, and then RabbitMQ will delete the message from the queue. If the consumer has an exception during the consumption process, the connection is disconnected and no response is sent. Then RabbitMQ will redeliver the message

所以我修改了我的代码

//message received event
consumer.Received += (ch, ea) =>
{
    var message = Encoding.UTF8.GetString(ea.Body);

    Console.WriteLine($"Received the news: {message}");

    Console.WriteLine($"received the message[{ea.DeliveryTag}] delay 10s to send receipt");
    Thread.Sleep(10000);
    //Confirm that the message has been consumed
    channel.BasicAck(ea.DeliveryTag, false);
    Console.WriteLine($"Receipt sent[{ea.DeliveryTag}]");
};

还是发送失败,没有回复,求助,谢谢!

我有一个发送消息的demo,你可以参考一下,可能会有帮助。

控制器:

    [Route("test")]
    public void Index()
    {
        try
        {
            var factory = new ConnectionFactory();
            factory.VirtualHost = "/";
            factory.HostName = "localhost";
            factory.Port = 5672;
            factory.UserName = "guest";//Default username guest
            factory.Password = "guest";//Default password guest
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "test",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                string message = "Hello World!";
                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: "",
                                     routingKey: "test",
                                     basicProperties: null,
                                     body: body);
                Console.WriteLine(" [x] Sent {0}", message);
            }

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.Write(string.Format("RabbitMQ connection error :{0}\n", ex.ToString()));
        }

    }

为了方便,我这里没有配置rabbitmq的连接信息。我直接写到方法里了,你自己做吧

结果: