Net中使用 RabbitMq | Message 消息內容

Message:它是服務器和應用程序之間傳送消息數據

Message:本質上就是一段數據,由Properties和PayLoad(Boby)組成

Message常用屬性

Delivery mode: 是否持久化,1 : Non-persistent(非持久化),2 : Persistent(持久化)
Headers:
自定義屬性:自定義屬性一般放到Headers中,進行發送
content_type : 消息內容的類型
content_encoding: 消息內容的編碼格式
priority: 消息的優先級,它的值一般是0-9,9的優先級最高
correlation_id:關聯id,在我們實際的工作中,一般把他作爲消息的唯一Id
reply_to: 用於指定回覆的隊列的名稱,比如某條消息發送失敗了讓它回到指定的隊列中
expiration: 消息的失效時間(毫秒)
message_id: 消息id
timestamp:消息的時間戳
type: 類型
user_id: 用戶id
app_id: 應用程序id
cluster_id: 集羣id

ProducterApp:生產者

using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;

namespace ProducterApp
{
    class Program
    {
        /// 連接配置
        /// </summary>
        private static readonly ConnectionFactory rabbitMqFactory = new ConnectionFactory() //創建一個工廠連接對象
        {
            HostName = "192.168.31.30",
            UserName = "admin",
            Password = "admin",
            VirtualHost = "/vhost001", //如果不設置,虛擬主機名稱路徑默認爲 /
            Port = 5672, //注意:5672 --是client端通信口   15672 -- 是管理界面ui端口           
        };
        /// <summary>
        /// 路由名稱
        /// </summary>
        const string ExchangeName = "exchange001";

        //隊列名稱
        const string QueueName = "queue001";
        static void Main(string[] args)
        {
            using (IConnection conn = rabbitMqFactory.CreateConnection()) //創建一個連接
            {
                using (IModel channel = conn.CreateModel()) //創建一個Channel
                {
                    channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null); //聲明一個Exchange(交換機)

                    channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null);//聲明一個隊列

                    string routingKey = "routing-" + QueueName;//這個routingKey的值可以隨便你自己設置,一般情況下直接設置爲QueueName的值就行
                    channel.QueueBind(QueueName, ExchangeName, routingKey: routingKey);


                    IBasicProperties props = channel.CreateBasicProperties();
                    props.DeliveryMode = 2; //1:非持久化 2:持續久化 (即:當值爲2的時候,我們一個消息發送到服務器上之後,如果消息還沒有被消費者消費,服務器重啓了之後,這條消息依然存在)
                    props.Persistent = true;
                    props.ContentEncoding = "UTF-8"; //注意要大寫
                    props.Expiration = "250000"; //消息過期時間爲25秒,(在這15秒之後如果消息沒有被消費,消息也過期了。當然你也可以不設置哦)

                    //props.UserId = "116";  //說實話這個userid我知道怎麼用
                    //props.MessageId = Guid.NewGuid().ToString("N");


                    //我們也可以設定自定義屬性,把自定義的屬性放到Headers中進行發送

                    var dir= new Dictionary<string, object>();
                    dir.Add("name", "張三");//特別要注意,字符串傳遞過去的時候是實際是以byte[]數組的形式傳遞過去的
                    dir.Add("age", 25);
                    props.Headers = dir;

                    for (int i = 0; i < 5; i++)
                    {
                        props.MessageId = Guid.NewGuid().ToString("N"); //設定這條消息的MessageId(每條消息的MessageId都是唯一的)

                        string msg = "你好,這是我的第" + i + "條消息;時間:" + DateTime.Now.ToString("yyyy:MM:dd");
                        var msgBody = Encoding.UTF8.GetBytes(msg); //發送的消息必須是二進制的
                        channel.BasicPublish(exchange: ExchangeName, routingKey: routingKey, basicProperties: props, body: msgBody);
                    }
                }
            }
        }
    }
}

CustomerApp:消費者

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

namespace CustomerApp
{
    class Program
    {
        /// <summary>
        /// 連接配置
        /// </summary>
        private static readonly ConnectionFactory rabbitMqFactory = new ConnectionFactory()
        {
            HostName = "192.168.31.30",
            UserName = "admin",
            Password = "admin",
            Port = 5672,
            VirtualHost = "/vhost001",
        };
        /// <summary>
        /// 路由名稱
        /// </summary>
        const string ExchangeName = "exchange001";
        //隊列名稱
        const string QueueName = "queue001";
        const string routingKey = "routing-" + QueueName;
        static void Main(string[] args)
        {
            using (IConnection conn = rabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    //創建交換機這裏將Exchange(交換機)Type設定爲fanout 【消費者端的交換機名稱要與生產者端的交換機名稱保持一致】
                    channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null);
                    //創建隊列【消費者端需要創建隊列,生產者端不需要創建隊列】
                    channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null);

                    channel.QueueBind(QueueName, ExchangeName, routingKey: routingKey); //fanout模式下Exchange與Queue綁定不需要指定RoutingKey,所以這裏設爲空字符串就行
                    while (true)
                    {
                        BasicGetResult msgResponse = channel.BasicGet(QueueName, autoAck: true);//這個true表示消費完這條數據是否刪除,true表示刪除,false表示不刪除
                        if (msgResponse != null)
                        {
                            var msgBody = Encoding.UTF8.GetString(msgResponse.Body);

                            var msgId = msgResponse.BasicProperties.MessageId;
                            //var userId = msgResponse.BasicProperties.UserId;


                            //這裏Header中的消息
                            byte[] namebyte = (byte[])msgResponse.BasicProperties.Headers["name"]; //這裏對objet進行強類型轉換爲byte[]                           
                            string name = Encoding.UTF8.GetString(namebyte);

                            int age = (int)msgResponse.BasicProperties.Headers["age"]; //年齡是int類型的直接強類型轉換

                            Console.WriteLine("姓名:{0}  年齡:{1}", name, age);

                            //這裏是Body中的消息
                            Console.WriteLine(string.Format("消息內容:{0};MessageId:{1}", msgBody, msgId));
                        }
                    }
                }
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章