使用阿里云的消息队列
一:引用Nuget包 Aliyun.AMQP
代码例子:
public class Program
{
static void Main(string[] args)
{
//发送消息队列
Publish("消息队列发送");
Console.WriteLine("发送成功");
//接收消息队列
Consume();
Console.WriteLine("接收成功");
Console.ReadKey();
}
/// <summary>
/// 连接阿里云消息队列
/// </summary>
/// <returns></returns>
public static ConnectionFactory CreateFactory()
{
var factory = new ConnectionFactory
{
HostName = "",//公网接入点
Port = 5672,
UserName = "",//AccessKey ID
VirtualHost = "",//Vhost
Password = "",//AccessKey Secret
AuthMechanisms = new List<AuthMechanismFactory>() { new AliyunMechanismFactory() },
TopologyRecoveryEnabled = true,
};
return factory;
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="message"></param>
/// <param name="queueName">消息队列名</param>
public static void Publish(string message, string queueName = null)
{
if (queueName == null)
{
queueName = "wolf_test";//消息队列名称
}
var factory = CreateFactory();
using (var connection = factory.CreateConnection())
{
using (var model = connection.CreateModel())
{
//消息持久化,防止丢失
model.QueueDeclare(queueName, true, false, false, null);
var properties = model.CreateBasicProperties();
properties.Persistent = true;
properties.DeliveryMode = 2;
//消息转换为二进制
var msgBody = Encoding.UTF8.GetBytes(message);
//消息发出到队列
model.BasicPublish("", queueName, properties, msgBody);
}
}
}
/// <summary>
/// 接收消息队列
/// </summary>
public static void Consume()
{
var factory = CreateFactory();
var connection = factory.CreateConnection();//连接阿里云消息队列
var ListenChannel = connection.CreateModel();
bool autoDeleteMessage = false;
var queue = ListenChannel.QueueDeclare("wolf_test", true, false, false, null);
//公平分发,不要同一时间给一个工作者发送多于一个消息
ListenChannel.BasicQos(0, 1, false);
//创建事件驱动的消费者类型,不要用下边的死循环来消费消息
var consumer = new EventingBasicConsumer(ListenChannel);
//consumer.Received += Consumer_Received;
//消费消息
ListenChannel.BasicConsume("wolf_test", autoDeleteMessage, consumer);
}
private void Consumer_Received(object sender, BasicDeliverEventArgs args)
{
var factory = CreateFactory();
var connection = factory.CreateConnection();
var ListenChannel = connection.CreateModel();
try
{
var body = args.Body;
var message = Encoding.UTF8.GetString(body);
//将消息业务处理交给外部业务
bool result = ReceiveMessageCallback(message);
if (result)
{
if (ListenChannel != null && !ListenChannel.IsClosed)
{
ListenChannel.BasicAck(args.DeliveryTag, false);
}
}
else
{
}
}
catch (Exception ex)
{
throw ex;
}
}
public Func<string, bool> ReceiveMessageCallback { get; set; }
}