筆記 RabbitMQ 的使用方式
本文連結
開發環境
- Windows 10
- VS2017 Enterprise
- RabbitMQ.Client 5.1.0
安裝 RabbitMQ Broker
安裝 Erlang
安裝 RabbitMQ
啟用管理介面
預設不會啟用這個服務,必須要手動啟用
rabbitmq-plugins enable rabbitmq_management
位置
預設管理員帳號 guest/guest
登入管理介面
guest 帳號只能在 localhost 執行,需要堤供外部使用者連接需要另件帳號,並給予權限
使用RabbitMQ.Client
PM> Install-Package rabbitmq.client
範例程式碼如下:
這裡只是用測試專案來 Survey RabbitMQ
https://github.com/yaochangyu/sample.dotblog/blob/master/RabbitMQ/Simple.RabbitMqDemo/UnitTestProject1/Queue.cs
[TestClass]
public class Queue
{
[TestMethod]
public void Sender()
{
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("Sent {0}", message);
}
}
[TestMethod]
public void Receive()
{
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 += (sender, args) =>
{
var body = args.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("Received {0}", message);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
}
}
}
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET