首页 > 解决方案 > RabbitMQ 连接被拒绝 127.0.0.1:5672

问题描述

我正在准备一个简单的 ASP.NET Core MVC Web 应用程序。

我已经在我的笔记本电脑上安装了 RabbitMQ 服务器。RabbitMQ 管理 UI 在localhost:15672.

Rabbit MQ 集群名称如下:rabbit@CR00001.ABC.COM.LOCAL

我正在尝试向控制器中的 rabbitmq 发送消息。但我得到None of the specified endpoints are reachable错误。

如果我使用 'localhost' 作为主机名,我会在内部异常中得到Connection denied 127.0.0.1:5672 。

如果我rabbit用作主机名,我会得到Name or service not known

我试图根据其他 StackOverflow 问题来解决问题,但是,没有一个可以解决我的问题。

家庭控制器:

        [HttpPost]
        public void SendMessage([FromBody]Message message)
        {
            try
            {
                var factory = new ConnectionFactory()
                {
                    UserName = _username,
                    Password = _password,
                    HostName = _hostname,
                    VirtualHost = "/",
                    Port = _port,
                };
                using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: _queueName,
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    var body = Encoding.UTF8.GetBytes(message.Text);

                    channel.BasicPublish(exchange: "",
                                         routingKey: _queueName,
                                         basicProperties: null,
                                         body: body);
                }

            }
            catch (Exception ex)
            {

            }
        }

应用设置.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "RabbitMq": {
    "Hostname": "localhost",
    "QueueName": "WordQueue",
    "UserName": "test",
    "Password": "test",
    "Port": 5672
  }
}

这是 Rabbit MQ 管理 UI 中的测试用户配置 测试用户配置

标签: asp.net.net-corerabbitmq

解决方案


创建用户后,不要忘记设置权限,基本上,

  • 可以访问虚拟主机 (/)

  • 设置主题权限(AMQP 默认) 注意:当然您可以使用 rabbitmq ui 进行此操作(创建用户和权限)。 在此处输入图像描述

    var factory = new ConnectionFactory() { HostName = "hostname_or_ip_adres_here", UserName="username here..", Password="psw here.." };

这会奏效!


推荐阅读