如何运用c#与RabbitMQ进行连接?

背景

最近被同事问到RabbitMQ相关的知识,因为之前没有接触过,所以趁着空闲时间学习了MQ的理论知识,光有理论知识最后的结果就是脑子看明白了,但是双手没学会,哈哈哈。那怎么行?当然要理论与实践相结合,下面给大家分享下如何运用c#与RabbitMQ进行连接,实现收发消息。

项目依赖

框架:.net framework 4.6.2

包依赖:RabbitMQ.Client 6.7.0

项目源码

https://github.com/MrJeanGao/MyRabbitMQ_Client

程序设计

前端页面设计如下:

包括了连接MQ需要的基本参数信息,消息发送的交换机和监听队列。(虚拟主机,交换机,队列之间的绑定关系通过RabbitMQ管理工具实现,没有在本程序中涉及)以及4个按钮,分别用于连接,断开,监听消息和发送消息。

代码实现

连接断开部分代码

private void button_connect_Click(object sender, EventArgs e)
        {
            try
            {
                string userName = textBox_userName.Text;
                string password = textBox_password.Text;
                string vHost = textBox_vHost.Text;
                string hostName = textBox_host.Text;
                RabbitMQ_Helper.ConnectMethod(userName, password, vHost, hostName);
                _channel = RabbitMQ_Helper._channel;
                _conn = RabbitMQ_Helper._conn;
                textBox_connectState.Text = connect;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }            
        }
private void button_disconnect_Click(object sender, EventArgs e)
        {
            RabbitMQ_Helper.DisconnectMethod();
            textBox_connectState.Text = disconnect;
        }

发送消息代码

private void button_send_Click(object sender, EventArgs e)
        {
            if ( _conn == null)
            {
                MessageBox.Show("先连接MQ!");
                return;
            }
            using (var channel = _conn.CreateModel())
            {
                string publishExchangeName = textBox_publishExchange.Text;
                string routingKey = "";
                string Message = textBox_sendContent.Text;
                bool result = SendMessage(channel, publishExchangeName, routingKey, Message);
                if (result)
                {
                    ShowLogMsg(sendTag, Message);
                }
            } // 在这里 channel 会被自动关闭和释放资源
            
        }
public bool SendMessage(IModel channel,string publishExchangeName, string routingKey, string Message)
        {
            try
            {
                byte[] messageBodyBytes = Encoding.UTF8.GetBytes(Message);
                IBasicProperties props = channel.CreateBasicProperties();
                props.ContentType = "text/plain";
                props.DeliveryMode = 2;
                channel.BasicPublish(publishExchangeName, routingKey, props, messageBodyBytes);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

监听消息代码 

private void button_listenMsg_Click(object sender, EventArgs e)
        {
            if (_conn == null)
            {
                MessageBox.Show("先连接MQ!");
                return;
            }
            if (string.IsNullOrEmpty(textBox_listenQueue.Text))
            {
                MessageBox.Show("ListenQueu不能为空!");
                return;
            }
            string listenQueue = textBox_listenQueue.Text;
            IModel channel = _conn.CreateModel();
            // 定义队列
            channel.QueueDeclare(queue: listenQueue, durable: true, 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);

                // 使用 Invoke 确保在 UI 线程上更新 TextBox
                richTextBox_showLog.Invoke(new Action(() =>
                {
                    ShowLogMsg(receivetag, message);
                }));
            };

            // 启动消费者监听队列
            channel.BasicConsume(queue: listenQueue, autoAck: true, consumer: consumer);
        }

消息收发展示

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值