1. 程式人生 > >.net 使用RabbitMQ demo

.net 使用RabbitMQ demo

rec 客戶端 object mar 其他 AI 消費者 str multipl

一、環境搭建就不重復了 上面有

二、在.NET中使用RabbitMQ需要下載RabbitMQ的客戶端程序集,可以到 官網下載 下載解壓後就可以得到RabbitMQ.Client.dll,這就是RabbitMQ的客戶端。

三、客戶端代碼

MQ_send(生產者)類

public class MQ_Send
{
public static void SendMSG(string queue_str, string msg ,bool durable) {
var factory = new ConnectionFactory();
factory.HostName = "192.168.0.*";
factory.UserName = "******";
factory.Password = "**********";
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
//queue 隊列名
// bool durable 是否持久化 是否設置消息持久化
//bool exclusive 是否獨有 排外
//bool autoDelete 是否自動刪除
//IDictionary<string, object> arguments 其他參數
channel.QueueDeclare(queue_str, durable, false, false, null);
string message = msg;
var body = Encoding.UTF8.GetBytes(message);
if (durable)
{
var properties = channel.CreateBasicProperties();
properties.SetPersistent(true);
channel.BasicPublish("", queue_str, properties, body);
}
else
{
channel.BasicPublish("", queue_str, null, body);
}
//Console.WriteLine(" set {0}", message);
}
}
}
}

主程序:

static void Main(string[] args)
{

#region 消息和隊列均不持久化

for (int i = 0; i < 4; i++)
{
MQ_Send.SendMSG("hello1", "測試", true);
}

#endregion
Console.ReadKey();

}

消費者主程序:

static void Main(string[] args)
{
var factory = new ConnectionFactory();
factory.HostName = "192.168.0.*";
factory.UserName = "******";
factory.Password = "**********";
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello1",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);

channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

Console.WriteLine(" [*] Waiting for messages.");

var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);

channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
channel.BasicConsume(queue: "hello1",
noAck: false,
consumer: consumer);

Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}

}

結束了 一般情況下都是用持久化的 人比較懶 直接上代碼 是程序都能看懂的

.net 使用RabbitMQ demo