RabbitMQ series of C# (2)--Hello World

Producer-Consumer Model

The last article discussed how to set up our development environment, no matter which language is used, the deployment of services must be the same.

From the official website : RabbitMQ is a message broker. In essence, it accepts messages from producers, and delivers them to consumers. In-between, it can route, buffer, and persist the messages according to rules you give it. (Translation: Rabbit ismessage broker, which essentially accepts messages fromproducersand distributes them toconsumers, in the processrouting,cachingandpersistingmessages according to your custom rules).
This article will start to create the first project based on the producer-consumer model, hello world, does it feel very cordial!

Since it is a producer-consumer model, it obviously means that we will have two sets of programs: producer and consumer. The producer is responsible for producing the message and pushing it to the queue, while the consumer pulls the message from the queue for processing.


producer

First we need to create a console application, the producer, the message sender, we create a class Send.cs, of course, if you want, you can also call it Producer.cs or F**k.cs and so on.
Remember, in the previous article, we have downloaded the driver, namely RabbitMQ.Client.dll, and now we only need to reference it in this project.

The code can be quoted like this (hey, the official website is so detailed, ape with a little common sense skips it directly)

using System;
using System.Text;
using RabbitMQ.Client;
  • 1
  • 2
  • 3

Next, you can create a connection with RabbitMQ Server:

class Send
{
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };//创建代理服务器实例。注意:HostName为Rabbit Server所在服务器的ip或域名,如果服务装在本机,则为localhost,默认端口5672
        using (var connection = factory.CreateConnection())//创建socket连接
        {
            using (var channel = connection.CreateModel())//channel中包含几乎所有的api来供我们操作queue
            {
                ...
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

It's very simple, right? Next, the complete code of Send.cs is given. For the convenience of understanding, I will write the comments in the code:

using System;
using RabbitMQ.Client;
using System.Text;

class Send
{
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using(var connection = factory.CreateConnection())
        using(var channel = connection.CreateModel())
        {
            //声明queue
            channel.QueueDeclare(queue: "hello",//队列名
                                 durable: false,//是否持久化
                                 exclusive: false,//true:排他性,该队列仅对首次申明它的连接可见,并在连接断开时自动删除
                                 autoDelete: false,//true:如果该队列没有任何订阅的消费者的话,该队列会被自动删除
                                 arguments: null);//如果安装了队列优先级插件则可以设置优先级

            string message = "Hello World!";//待发送的消息
            var body = Encoding.UTF8.GetBytes(message);

            channel.BasicPublish(exchange: "",//exchange名称
                                 routingKey: "hello",//如果存在exchange,则消息被发送到名称为hello的queue的客户端
                                 basicProperties: null,
                                 body: body);//消息体
            Console.WriteLine(" [x] Sent {0}", message);
        }

        Console.WriteLine(" Press [enter] to exit.");
        Console.ReadLine();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

OK, then start the program, and our message is pushed to the queue on the Rabbit Server, waiting for the client to connect, that is, waiting for the consumer to pull. As shown below:


consumer

This time, recreate the console application, and the class name is Receive.cs. Similarly, you can name it with your own comfortable words.

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

class Receive
{
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using(var connection = factory.CreateConnection())
        using(var channel = connection.CreateModel())
        {
            channel.QueueDeclare(queue: "hello",//指定发送消息的queue,和生产者的queue匹配
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            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.BasicConsume(queue: "hello",
                                 noAck: true,//和tcp协议的ack一样,为false则服务端必须在收到客户端的回执(ack)后才能删除本条消息
                                 consumer: consumer);

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

Is this code similar to Send? Yes, there is no difference between creating a connection and declaring a queue!
Running the program, the effect is as follows:

even if your Send program is closed, as long as it has been run and successfully sent, the queue will keep saving the messages until the client connects, and these messages will be sent to the consumer.
You can experiment like this, start Send.exe in the debug directory of bin, 3 times in a row, and then run the client, you will receive 3 messages, as shown below:

So far, our Hello World has run successfully. Of course, this small demo is not just used to say hello, but more to help me understand the basic principles of rabbits and provide a solution in high concurrency situations. I believe that it can be used when the company's mall develops and grows in the future! ! !

Looking forward to the next one!


Guess you like

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