using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client;
using System.Threading;
using RabbitMQ.Client.Exceptions;
namespace amqp_dotnetframework_demo
{
class Program
{
static void Main(string[] args) {
// 测试队列的名称
string QueueName = "helloworldqueue";
var factory = new ConnectionFactory();
/* 接入点 */
factory.HostName = "********";
/* 阿里云的 accessKey*/
factory.UserName = "********";
/* 阿里云的 accessSecret*/
factory.Password = "********";
// 虚拟主机的名称, 需要提前在管理门户创建
factory.VirtualHost = "********";
/* 默认端口 */
factory.Port = 5672;
factory.AuthMechanisms = new List<AuthMechanismFactory>() { new AliyunMechanismFactory() };
factory.TopologyRecoveryEnabled = true;
ConnectionFactory rabbitMqFactory = factory;
// 发送消息测试
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
channel.QueueDeclare(queue: QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
while (true)
{
try
{
if (!connection.IsOpen)
{
connection.Close();
connection = factory.CreateConnection();
channel = connection.CreateModel();
}
string message = Guid.NewGuid().ToString();
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "", routingKey: QueueName, basicProperties: null, body: body);
Console.WriteLine("[x] Sent {0}", message);
Thread.Sleep(1000);
}
catch (BrokerUnreachableException e)
{
Thread.Sleep(3000);
Console.WriteLine(e);
continue;
}
catch (Exception e)
{
Console.WriteLine(e);
continue;
}
}
Console.ReadKey();
}
}
}
来源: https://yq.aliyun.com/articles/699103