C# WPF RabbitMq收发消息实例解析

概述

     在项目开发中rabbitmq常用来进行消息收发,这节我通过一个简单的实例来演示在C#中如何进行应用rabbitmq.


首先要在nuget上引用rabbitmq.client:如下图

C# WPF RabbitMq收发消息实例解析_第1张图片

最终的效果图:

C# WPF RabbitMq收发消息实例解析_第2张图片

源码讲解

     前台XMAL:


    
        
            
                
            
        
    


    
        
            
            
        
        
            
            
        


        
            


        
            


        

这里左边是要发送的消息,右边是接受到的消息,每次点击start execute后会发送10条消息.

后台cs逻辑代码:

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace Caliburn.Micro.Hello.ViewModels
{
    public class RabbitMqViewModel : Screen, IViewModel
    {
        private static string queueName = "simple_order";//队列名
        private StringBuilder stringBuilder1 = new StringBuilder();
        private StringBuilder stringBuilder2 = new StringBuilder();
        public string DisplayInfo1 { get; set; }
        public string DisplayInfo2 { get; set; }
        public RabbitMqViewModel()
        {
            DisplayName = "RabbitMq";
        }
        public void StartExecute()
        {
            Task.Run(() =>
            {
                SimpleSendMsg("Hello RabbitMQ");
            });
            Task.Run(() =>
            {
                SimpleConsumer();
            });
        }


        public void SimpleSendMsg(string message)
        {
            //创建连接
            using (var connection = RabbitMQHelper.GetConnection())
            {
                //创建信道
                using (var channel = connection.CreateModel())
                {//创建队列
                    channel.QueueDeclare(queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);


                    for (var i = 0; i < 10; i++)
                    {
                        var body = Encoding.UTF8.GetBytes(message);//发送消息
                        channel.BasicPublish(exchange: "", routingKey: queueName, mandatory: false, basicProperties: null, body);
                        stringBuilder1.AppendLine($"发送消息到队列:{queueName},内容:{message}");
                        Execute.OnUIThread(() =>
                        {
                            DisplayInfo1 = stringBuilder1.ToString();
                        });
                        Thread.Sleep(1000);
                    }
                }
            }
        }


        public void SimpleSendMsg()
        {
            //创建连接
            using (var connection = RabbitMQHelper.GetConnection())
            {
                //创建信道
                using (var channel = connection.CreateModel())
                {//创建队列
                    channel.QueueDeclare(queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
                    for (var i = 0; i < 10; i++)
                    {
                        string message = $"Hello RabbitMQ MessageHello,{i + 1}";
                        var body = Encoding.UTF8.GetBytes(message);//发送消息
                        channel.BasicPublish(exchange: "", routingKey: queueName, mandatory: false, basicProperties: null, body);
                        stringBuilder1.AppendLine($"发送消息到队列:{queueName},内容:{message}");
                        Execute.OnUIThread(() =>
                        {
                            DisplayInfo1 = stringBuilder1.ToString();
                        });
                    }
                }
            }
        }


        public void SimpleConsumer()
        {
            var connection = RabbitMQHelper.GetConnection();
            {
                //创建信道
                var channel = connection.CreateModel();
                {
                    //创建队列
                    channel.QueueDeclare(queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
                    var consumer = new EventingBasicConsumer(channel);
                    int i = 0;
                    consumer.Received += (model, ea) =>
                    {
                        //消费者业务处理
                        var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                        stringBuilder2.AppendLine($"{i},队列{queueName}消费消息长度:{message.Length},内容 = {message}");
                        Execute.OnUIThread(() =>
                        {
                            DisplayInfo2 = stringBuilder2.ToString();
                        });
                        i++;
                    };
                    channel.BasicConsume(queueName, true, consumer);
                }
            }
        }
    }


    /// 
    /// RabbitMQ帮助类
    /// 
    public class RabbitMQHelper
    {
        private static ConnectionFactory factory;
        private static object lockObj = new object();
        /// 
        /// 获取单个RabbitMQ连接
        /// 
        /// 
        public static IConnection GetConnection()
        {
            if (factory == null)
            {
                lock (lockObj)
                {
                    if (factory == null)
                    {
                        factory = new ConnectionFactory
                        {
                            HostName = "localhost",//"172.16.2.84",//ip
                            Port = 5672,//端口
                            UserName = "guest",//账号
                            Password = "guest",//密码
                            //VirtualHost = "develop" //虚拟主机
                        };
                    }
                }
            }
            return factory.CreateConnection();
        }
    }


}

这里RabbitMQHelper封装了一个单例模式的RabbitMQ连接,SimpleSendMsg方法用来发送消息,SimpleConsumer用来消费消息,具体的rabbitmq服务端搭建可以百度搜索.

StartExecute方法里面开了两个线程一个用来发送消息一个用来接收消息.

源码下载

百度网盘链接:

https://pan.baidu.com/s/13_3UrCyDHIghWp5nkbiBXw

提取码:6666

技术群:添加小编微信sf-1738658853

公众号:dotnet讲堂

你可能感兴趣的:(rabbitmq,c#,wpf,分布式,开发语言)