The use of RabbitMQ under .Net (2) -- sending and receiving messages

After installing and configuring RabbitMQ, we can try to do the simplest example: sending and receiving messages.

 

Let's first look at the code of the client, which is the sender:

using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SendService
{
    class Program
    {
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory();
            factory.HostName = "192.168.12.111";
            factory.Port = 5672;
            factory.UserName = "admin";
            factory.Password = "admin";

            //Define the data to send

            List<RequestMessage> messages = new List<RequestMessage>();
            for (int i = 0; i < 200;i++ )
            {
                RequestMessage message = new RequestMessage() { MessageId = Guid.NewGuid(), Message = "this is a 请求。" + i };
                messages.Add(message);
            }
            
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("all.sms.message", false, false, false, null);//hello is the name of the queue
                    //Serialize message objects, RabbitMQ does not support serialization of complex objects, so you need to serialize your own types for custom types
                    foreach (var item in messages)
                    {
                        XmlSerializer xs = new XmlSerializer(typeof(RequestMessage));
                        using (MemoryStream ms = new MemoryStream())
                        {

                            xs.Serialize(ms, item);

                            byte[] bytes = ms.ToArray();

                            //Specify the sending route and send it directly to the specified queue through the default exchange.

                            channel.BasicPublish("", "all.sms.message", null, bytes);
                            Console.WriteLine(" [x] Sent {0}", item.Message);
                        }
                    }
                    //var body = Encoding.UTF8.GetBytes(message);
                    //channel.BasicPublish("", "all.sms.message", null, body);//hello is the name of the routing key
                     
                    Console.ReadLine();
                }
            }
        }
    }

    public class RequestMessage
    {
        public Guid MessageId { set; get; }
        public string Message { set; get; }
    }
}

 

in method
channel.BasicPublish("", "esbtest.rmq.consoleserver", null, bytes);
The first parameter in is required to enter an exchange. In RabbitMQ, all messages must be sent to each queue through exchange. When the sender sends a message, it actually puts the message in the exchange. And the exchange knows where to put the message. In this method, we did not enter the name of the exchange, but just defined an empty exchange, and entered the name of our target queue in the second parameter routeKey. RabbitMQ will help me define a default exchange, which will deliver messages directly to
We enter the queue, so the server only needs to go directly to this defined queue to get messages.
Server-side code:
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ReceiveService
{
    class Program
    {
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory();
            factory.HostName = "192.168.12.111";
            factory.Port = 5672;
            factory.UserName = "admin";
            factory.Password = "admin";
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("all.sms.message", false, false, false, null);//hello is the name of the queue
                    Console.WriteLine("Listening...");
                    //Define a consumer on the queue
                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume("all.sms.message", true, consumer);//hello is the name of the queue, here it can be understood that hello is the name of the routing key. Because this example doesn't use an exchange with the specified name (it actually uses the default exchange name), the queue name is the same as the routing key name. In the fifth article, the relationship and usage of queue name and routing key are introduced if an exchange with a specified name is used.
                    Console.WriteLine(" [*] Waiting for messages." + "To exit press CTRL+C");
                    while (true)
                    {
                        //Blocking function, get the message in the queue
                        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//阻塞
                        byte[] body = ea.Body;
                        XmlSerializer xs = new XmlSerializer(typeof(RequestMessage));
                        using (MemoryStream ms = new MemoryStream(body))
                        {

                            RequestMessage message = (RequestMessage)xs.Deserialize(ms);

                            Console.WriteLine("Receive a Message, Id:" + message.MessageId + " Message:" + message.Message);

                        }
                        //Console.ReadLine();
                        //var message = Encoding.UTF8.GetString(body);
                        //Console.WriteLine(" [x] Received {0}", message);
                    }
                }
            }  
        }
    }

    public class RequestMessage
    {
        public Guid MessageId { set; get; }
        public string Message { set; get; }
    }
}
 

At this point, the simple sending and receiving program can be run, run RabbitMQ, and then run the client and server respectively. The running result is shown in the figure:

Client:

image

 

Server:

server

Guess you like

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