在 .NET 中使用 RabbitMQ 的步骤如下:
- 安装 RabbitMQ
首先,您需要在系统上安装 RabbitMQ。您可以从 RabbitMQ 官方网站下载适用于您所使用的操作系统的安装程序。如果您使用的是 Windows 操作系统,则可以从 Microsoft 官网下载安装程序。
- 安装 RabbitMQ 客户端库
dotnet add package RabbitMQ.Client
- 编写 RabbitMQ 生产者代码
以下是使用 RabbitMQ 发送消息的示例代码。
using System; using System.Text; using RabbitMQ.Client; using RabbitMQ.Client.Events; class Program { static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost" }; using (IConnection connection = factory.CreateConnection()) using (IModel channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); string message = "Hello World!"; byte[] 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(); } }
- 编写 RabbitMQ 消费者代码
以下是使用 RabbitMQ 接收消息的示例代码。
using System; using System.Text; using RabbitMQ.Client; using RabbitMQ.Client.Events; class Program { static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost" }; using (IConnection connection = factory.CreateConnection()) using (IModel channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { byte[] body = ea.Body; string 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(); } } }
以上示例代码将 "Hello World!" 消息发送到 "hello" 队列中,然后将此消息收到并打印到控制台。
注意:在使用 RabbitMQ 前,请确保已经在计算机上安装 RabbitMQ 和 .NET RabbitMQ 客户端库。 标签:Console,false,RabbitMQ,rabbitmq,使用,using,net,message,channel From: https://www.cnblogs.com/UsefulIdiot/p/17506786.html