在C#中使用RabbitMQ進行消息隊列處理需要使用RabbitMQ的官方客戶端庫RabbitMQ.Client。以下是一個簡單的示例代碼,演示如何在C#中使用RabbitMQ發送和接收消息:
using RabbitMQ.Client;
using System;
using System.Text;
class Program
{
static void Main()
{
// 連接到RabbitMQ服務器
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);
// 接收消息
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服務器,然后聲明一個名為"hello"的隊列。我們發送一條消息"Hello World!"到這個隊列,然后從該隊列接收消息并打印出來。最后,按下回車鍵退出程序。
請確保在運行此示例之前已經安裝了RabbitMQ服務器,并且RabbitMQ.Client庫已經安裝到您的C#項目中。