Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

rabbitmq c#

作者:木の兮   发布日期:2025-06-02   浏览:94

using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        // 创建连接工厂并设置参数
        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 bodyReceived = ea.Body.ToArray();
                    var messageReceived = Encoding.UTF8.GetString(bodyReceived);
                    Console.WriteLine(" [x] Received {0}", messageReceived);
                };

                channel.BasicConsume(queue: "hello",
                                     autoAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
        }
    }
}

解释说明:

  1. 创建连接工厂:通过 ConnectionFactory 类创建一个连接工厂,并设置主机名为 "localhost",表示连接到本地的 RabbitMQ 服务器。
  2. 创建连接和通道:使用连接工厂创建一个连接,并通过该连接创建一个通道。RabbitMQ 中的所有操作都是通过通道完成的。
  3. 声明队列:使用 QueueDeclare 方法声明一个名为 "hello" 的队列,确保该队列存在。如果队列已经存在,则不会重复创建。
  4. 发送消息:将字符串消息转换为字节数组,并通过 BasicPublish 方法发送到指定的队列中。
  5. 接收消息:创建一个 EventingBasicConsumer 消费者对象,并为其注册 Received 事件处理程序,当有消息到达时触发该事件。使用 BasicConsume 方法开始消费队列中的消息。
  6. 控制台输出:在发送和接收消息时,分别输出相应的提示信息。

如果你需要更复杂的示例或有其他问题,请随时告诉我!

上一篇:c#字符串转日期

下一篇:c#websocket

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站