.NET 雲原生架構師訓練營(模組二 基礎鞏固 RabbitMQ HelloWorld)–學習筆記
- 2021 年 1 月 9 日
- 筆記
- 【002】.NET Core, 【008】.NET 雲原生架構師訓練營
2.6.3 RabbitMQ — HelloWorld
- 發送端
- 接收端
- rabbitmq container
- 發送資訊
//www.rabbitmq.com/tutorials/tutorial-one-dotnet.html
新建控制台項目 Sender,Receiver
添加 nuget 包:RabbitMQ.Client
發送端
namespace Sender
{
class Sender
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false, // 持久化
exclusive: false, // 排它
autoDelete: false, // 自動刪除
arguments: null);
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
接收端
namespace Receiver
{
class Receiver
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
rabbitmq container
docker run -d -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
運行成功後可以訪問(localhost 替換為伺服器地址)
//localhost:15672/#/
用戶名密碼默認為 guest
替換髮送端,接收端的 localhost 為伺服器地址
發送資訊
先啟動接收端,再啟動發送端
發送多條資訊
Sender
channel.QueueDeclare(queue: "hello",
durable: false, // 持久化
exclusive: false, // 排它
autoDelete: false, // 自動刪除
arguments: null);
Console.WriteLine("Please input your message with enter:");
string message = Console.ReadLine();
while (message != "EXIT")
{
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
Console.WriteLine("Please input your message with enter:");
message = Console.ReadLine();
}
先啟動接收端,再啟動發送端
GitHub源碼鏈接:
//github.com/MINGSON666/Personal-Learning-Library/tree/main/ArchitectTrainingCamp
本作品採用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。
歡迎轉載、使用、重新發布,但務必保留文章署名 鄭子銘 (包含鏈接: //www.cnblogs.com/MingsonZheng/ ),不得用於商業目的,基於本文修改後的作品務必以相同的許可發布。
如有任何疑問,請與我聯繫 ([email protected]) 。