C # rabbitmq simple sending and receiving message example code

Time:2021-1-28

Announcement: (producer)

/// <summary>
    ///Send message
    /// </summary>
    ///< param name = "queue" > queue name < / param >
    ///< param name = "message" > message content < / param >
    private static void PublishInfo(string queue, string message)
    {
      try
      {
        var factory = new ConnectionFactory();
        factory.HostName  ="Localhost"; // rabbitmq service runs locally
        factory.UserName  ="Guest"; // user name
        factory.Password  ="Guest"; // password

        using (var connection = factory.CreateConnection())
        {
          using (var channel = connection.CreateModel())
          {
            Bool durable = true; // mark message as persistent
            channel.QueueDeclare(queue, durable, false, false, null);

            IBasicProperties properties = channel.CreateBasicProperties();
            properties.DeliveryMode = 2;

            var body = Encoding.UTF8.GetBytes(message);
            channel.BasicPublish (", queue, properties, body); // start delivery

          }
        }
      }
      catch (System.Exception ex)
      {
        Console.WriteLine(ex.ToString());
      }
      Console.ReadLine();
    }

use:


PublishInfo("test", "222222222222");

Click test to enter the queue:

Consumer news:

Method 1: the old version is available

private static void ConsumeInfo(string queue)
    {
      try
      {
        var factory = new ConnectionFactory();
        factory.HostName  ="Localhost"; // rabbitmq service runs locally
        factory.UserName  ="Guest"; // user name
        factory.Password  ="Guest"; // password

        using (var connection = factory.CreateConnection())
        {
          using (var channel = connection.CreateModel())
          {
            //Bool durable = true; // mark message as persistent
            // channel.QueueDeclare (" sljcgx:finish-queue ", durable, false, false, null); // declare the queue. If the queue does not exist, create the queue

            //Set prefetchcount: 1 to inform rabbitmq that no message will be distributed when the consumer's message confirmation is not received, which ensures that no task will be assigned when the consumer is busy.
            channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
            var consumer = new QueueingBasicConsumer(channel);
           
            //False is the manual confirmation, which needs to be added after obtaining the message channel.BasicAck ( ea.DeliveryTag , false) confirm
            //True is automatic confirmation, and this line of code is not required
            channel.BasicConsume(queue, false, consumer);

            while (true)
            {
              try
              {
                var ea = (BasicDeliverEventArgs) consumer.Queue.Dequeue (); // block function to get messages in the queue
                var bodyReceive = ea.Body;
                string message = Encoding.UTF8.GetString(bodyReceive);
                Console.WriteLine(message);
                channel.BasicAck ( ea.DeliveryTag , false); // the message confirmation signal. After confirmation, the message will be removed from the queue
              }
              catch (System.Exception ex)
              {
                
                Console.WriteLine(ex.Message);
              }
            }
          }

        }
      }
      catch (System.Exception ex)
      {
        Console.WriteLine(ex.ToString());
      }
      Console.ReadLine();
    }

Method 2: (general)

private static void ConsumeInfo2(string queue)
    {
      try
      {
        var factory = new ConnectionFactory();
        factory.HostName  ="Localhost"; // rabbitmq service runs locally
        factory.UserName  ="Guest"; // user name
        factory.Password  ="Guest"; // password
        var connection = factory.CreateConnection();
        var channel = connection.CreateModel();
        channel.QueueDeclare (queue, true, false, false, null); // declare the queue. If the queue does not exist, create the queue
        channel.BasicQos (0, 1, false); // fair distribution, processing only one message at a time.

        Var consumer = new eventingbasicconsumer (channel); // consumer (specify message channel). This event is triggered when a message is received
        consumer.Received += (sender, e) =>
        {
          byte[] body = e. Body.ToArray (); // message byte array
          string message =  Encoding.UTF8 . getString (body); // message content

          Console.WriteLine(message);
          channel.BasicAck (e.deliverytag, false); // confirm manually

        };
        channel.BasicConsume (queue, false, consumer); // consume messages (listen to the queue in the current channel and consume)
        Console.ReadLine();
        connection.Close();
        channel.Close();
      }
      catch (System.Exception ex)
      {
        Console.WriteLine(ex.ToString());
      }
    }

This article about C # rabbitmq simple message sending and receiving sample code is introduced here. For more information about C # rabbitmq message sending and receiving content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!