【微服務專題之】.Net6下集成消息隊列上-RabbitMQ ...
微信公眾號:趣編程ACE
關註可瞭解更多的.NET日常實戰開發技巧,如需源碼 請公眾號後臺留言 源碼;
[如果覺得本公眾號對您有幫助,歡迎關註]
.Net中RabbitMQ的使用
超清觀看視頻哦~
代碼演示
-詳細見代碼註釋,操作看上文視頻
生產者代碼
1using RabbitMQ.Client;
2using System.Text;
3
4
5// 創建一個連接工廠
6var factory = new ConnectionFactory()
7{
8 Uri = new Uri("amqp://guest:guest@localhost:5672")
9};
10// 工廠開始連接
11using (var connection = factory.CreateConnection())
12// 創建一個連接通道
13using (var channel = connection.CreateModel())
14{
15 channel.QueueDeclare(queue: "hello",
16 // 持久性 一直保持 直到消費者 消費隊列
17 durable: true,
18 // 獨占
19 exclusive: false,
20 autoDelete: false,
21 arguments: null);
22
23 // 發送的消息
24 string message = "Hello World!";
25 var body = Encoding.UTF8.GetBytes(message);
26
27 // 基本發佈 不指定交換
28 channel.BasicPublish(exchange: "",
29 // 路由鍵 就是隊列名稱
30 routingKey: "hello",
31 // 基礎屬性
32 basicProperties: null,
33 // 傳遞的消息體
34 body: body);
35 Console.WriteLine(" [x] Sent {0}", message);
36}
37
38Console.WriteLine(" Press [enter] to exit.");
39Console.ReadLine();
消費者代碼
1using RabbitMQ.Client;
2using RabbitMQ.Client.Events;
3using System.Text;
4
5// 創建一個連接工廠
6var factory = new ConnectionFactory()
7{
8 Uri = new Uri("amqp://guest:guest@localhost:5672")
9};
10using (var connection = factory.CreateConnection())
11using (var channel = connection.CreateModel())
12{
13 channel.QueueDeclare(queue: "hello",
14 durable: true,
15 exclusive: false,
16 autoDelete: false,
17 arguments: null);
18
19 // 創建一個消費者基本事件
20 var consumer = new EventingBasicConsumer(channel);
21 consumer.Received += (model, ea) =>
22 {
23 var body = ea.Body.ToArray();
24 var message = Encoding.UTF8.GetString(body);
25 Console.WriteLine(" [x] Received {0}", message);
26 };
27 channel.BasicConsume(queue: "hello",
28 // 自動確認
29 autoAck: true,
30 consumer: consumer);
31
32 Console.WriteLine(" Press [enter] to exit.");
33 Console.ReadLine();
環境安裝
docker下安裝RabbitMQ鏡像
1// 詳細解釋看視頻
2docker run -d --hostname my-rabbit --name rabbitmq -p 15672:15672 -p 5672:5672 rabbitmq
3
4//這一段必須需要 否則網站起不來 其中 c71119561de6 為容器ID
5docker exec -it c71119561de6 rabbitmq-plugins enable rabbitmq_management
RabbitMQ是個輕量級,易部署的隊列,我會根據官網指導,分享一系列常用使用技巧的,隨時保持關註哦~