.net using RabbitMQ demo

1. The environment construction will not be repeated. There are

2. To use RabbitMQ in .NET, you need to download the RabbitMQ client assembly. You can go to the official website to download,  download and decompress it and you can get RabbitMQ.Client.dll, which is the RabbitMQ client.

3. Client code

       MQ_send (producer) class

       

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 queue name
// Whether bool durable is persistent or not to set message persistence
//bool exclusive is exclusive exclusive
//bool autoDelete is automatically deleted
//IDictionary<string, object> arguments other parameters
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);
}
}
}
}

 

Main program:

static void Main(string[] args)
{

#region messages and queues are not persisted

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

#endregion
Console.ReadKey();

}

 

Consumer main program:

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();
}

}

It's over. In general, people who use persistence are lazy, and the code can be understood by the program directly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325020655&siteId=291194637