.net 使用RabbitMQ demo

一、环境搭建就不重复了 上面有

二、在.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();
}

}

结束了 一般情况下都是用持久化的  人比较懒 直接上代码 是程序都能看懂的

原文地址:https://www.cnblogs.com/mintworld/p/8970713.html