阅读量:0
在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#项目中。