RabbitMQ使用

RabbitMQ使用,第1张

RabbitMQ使用

开发必备及常用工具汇总

首先安装RabbitMQ的必备环境

1.下载并安装Erlang基础环境及Rabbit-Server

2.启动RabbitMQ Server
点击Windows开始按钮,输入RabbitMQ找到RabbitMQ Comman prompt,以管理员身份运行。
依次执行以下命令启动RabbitMQ服务

rabbitmq-service install
rabbitmq-service enable
rabbitmq-service start

执行rabbitmqctl status检查RabbitMQ状态

安装管理平台插件

执行rabbitmq-plugins enable rabbitmq_management即可成功安装,使用默认账号密码(guest/guest)登录http://localhost:15672/即可。

编码
Install-package RabbitMQ.Client

发送端:

static void Main(string[] args)
        {
            //1.1.实例化连接工厂
            var factory = new ConnectionFactory() { HostName = "localhost" };
            //2. 建立连接
            using (var connection = factory.CreateConnection())
            {
                //3. 创建信道
                using (var channel = connection.CreateModel())
                {
                    //4. 申明队列
                    channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    //5. 构建byte消息数据包
                    string message = args.Length > 0 ? args[0] : "Hello RabbitMQ!";
                    var body = Encoding.UTF8.GetBytes(message);
                    //6. 发送数据包
                    channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
            }
        }

接收端:

static void Main(string[] args)
        {
            //1.实例化连接工厂
            var factory = new ConnectionFactory() { HostName = "localhost" };
            //2. 建立连接
            using (var connection = factory.CreateConnection())
            {
                //3. 创建信道
                using (var channel = connection.CreateModel())
                {
                    //4. 申明队列
                    channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    //5. 构造消费者实例
                    var consumer = new EventingBasicConsumer(channel);
                    //6. 绑定消息接收后的事件委托
                    consumer.Received += (model, ea) =>
                    {
                        var message = Encoding.UTF8.GetString(ea.Body);
                        Console.WriteLine(" [x] Received {0}", message);
                        Thread.Sleep(6000);//模拟耗时
                        Console.WriteLine(" [x] Done");
                    };
                    //7. 启动消费者
                    channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);
                    Console.WriteLine(" Press [enter] to exit.");
                    Console.ReadLine();
                }
            }
        }

执行效果

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5706660.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存