这通常是由于RabbitMQ地址或端口不正确或RabbitMQ未启动而导致的。要解决此问题,可以尝试以下步骤:
-
检查RabbitMQ地址和端口是否正确。
-
检查RabbitMQ是否已启动。可以尝试使用命令行或RabbitMQ管理界面来确认。
-
确认你的应用程序具有连接到RabbitMQ的正确的凭据和权限。
以下是C#示例代码,它演示了如何创建连接并在RabbitMQ上发送消息:
var factory = new ConnectionFactory() {
HostName = "localhost",
UserName = "guest",
Password = "guest"
};
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
如果上述步骤无法解决问题,则需要进一步调试和排除错误。