溫馨提示×

如何使用C# RabbitMQ進(jìn)行消息的發(fā)送和接收

c#
小樊
186
2024-08-13 09:48:40
欄目: 編程語言

要使用C# RabbitMQ進(jìn)行消息的發(fā)送和接收,首先需要安裝RabbitMQ的客戶端庫,可以使用NuGet包管理器來安裝。然后,您需要編寫發(fā)送和接收消息的代碼。

以下是一個(gè)簡單的示例代碼,演示如何在C#中使用RabbitMQ發(fā)送和接收消息:

  1. 發(fā)送消息:
using RabbitMQ.Client;
using System;
using System.Text;

class Program
{
    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();
    }
}
  1. 接收消息:
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

class Program
{
    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();
        }
    }
}

在這個(gè)示例中,發(fā)送端將消息發(fā)送到名為“hello”的隊(duì)列中,接收端從該隊(duì)列中接收消息并打印到控制臺(tái)。您可以根據(jù)需要修改代碼來滿足您的需求。

0