Net下RabbitMQ消息队列的使用

写在前面


整个项目就是实现C#客户端往消息队列生产消息,消费消息。


环境搭建


1、Erlang安装

 RabbitMQ由ERLANG实现,故需要安装Erlang。
1)下载Erlang
    下载官网: http://www.erlang.org/download.html
    实践安装版本:otp_win64_19.0.exe。
2)安装Erlang
    运行Exe按照提示一路Next安装下来。
3)配置Erlang
    本机安装目录:D:\Program Files\erl8.0
    环境变量Path中添加D:\Program Files\erl8.0\bin




4) 检测Erlang
    命令行中输入erl命令可检测Erlang是否安装成功。




2、RabbitMQ安装


 对应RabbitMQ的版本为V3.6.5。
1)下载RabbitMQ
    对应官网: http://www.rabbitmq.com/download.html
    下载安装包:rabbitmq-server-3.6.5.exe。
2)安装RabbitMQ
    运行Exe,一路Next安装完毕。

3)安装完成查看

扫描二维码关注公众号,回复: 2376718 查看本文章




3、RabbitMQ启动


1)启动管理插件
    运行RabbitMQ Command Prompt(sbin dir)。
    输入rabbitmq-plugins enable rabbitmq_management,启动管理插件。

2)启动管理服务
    运行rabbitmq-service.bat start。
3)登录管理界面
    浏览器输入:http://localhost:15672/#/。

    用户名:guest,密码guest。




生产者消费者

示例代码采用C#,对应IDE为VS2013。
需要用到RabbitMQ .NET/C# client library
RabbitMQ .NET/C# client library下载地址:http://www.rabbitmq.com/dotnet.html

解压缩,里面存在RabbitMQ.Client.dll文件。

VS2013新建一个C#控制台项目,添加引用,把上面下载的RabbitMQ.Client.dll添加进来。
新建一个类MyRabbitMq,具体代码如下

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7.   
  8. using System.IO;  
  9. using System.Threading;  
  10. using RabbitMQ.Client;  
  11.   
  12.   
  13.   
  14.   
  15. namespace RabbitmqClient  
  16. {  
  17.     /// <summary>  
  18.     /// P2P模式,即一个生产者一个消费者  
  19.     /// </summary>  
  20.     public class MyRabbitMq  
  21.     {  
  22.         private readonly ConnectionFactory rabbitMqFactory;  
  23.         const string ExchangeName = "test.exchange";  
  24.         const string QueueName = "test.queue";  
  25.   
  26.   
  27.         public MyRabbitMq(bool isLocal = truestring remoteAddress = "localhost")  
  28.         {  
  29.             if (isLocal)  
  30.                 rabbitMqFactory = new ConnectionFactory { HostName = "localhost" };  
  31.             else   
  32.                 rabbitMqFactory = new ConnectionFactory { HostName = remoteAddress };  
  33.         }  
  34.   
  35.   
  36.         public void Register_durable_Exchange_and_Queue()  
  37.         {  
  38.             using (IConnection conn = rabbitMqFactory.CreateConnection())  
  39.             using (IModel channel = conn.CreateModel())  
  40.             {  
  41.                 channel.ExchangeDeclare(exchange: ExchangeName, type: "direct", durable: true, autoDelete: false, arguments: null);  
  42.                 channel.QueueDeclare(queue: QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);  
  43.                 channel.QueueBind(queue: QueueName, exchange: ExchangeName, routingKey: QueueName);  
  44.             }  
  45.         }  
  46.   
  47.   
  48.         /// <summary>  
  49.         /// 生产者,插入消息  
  50.         /// </summary>  
  51.         /// <param name="message">消息</param>  
  52.         /// <param name="persistent">是否持久化</param>  
  53.         public void SendMessage(string message, bool persistent = true)  
  54.         {  
  55.             using (IConnection conn = rabbitMqFactory.CreateConnection())  
  56.             using (IModel channel = conn.CreateModel())  
  57.             {  
  58.                 var props = channel.CreateBasicProperties();  
  59.                 if (persistent)  
  60.                 {  
  61.                     props.Persistent = true;                  
  62.                 }  
  63.   
  64.   
  65.                 var msgBody = Encoding.UTF8.GetBytes(message);  
  66.                 channel.BasicPublish(exchange: ExchangeName, routingKey: QueueName, basicProperties: props, body: msgBody);  
  67.   
  68.   
  69.                 Console.WriteLine(" [x] Sent {0}", message);  
  70.             }  
  71.         }  
  72.   
  73.   
  74.         /// <summary>  
  75.         /// 消费者,取出消息  
  76.         /// </summary>  
  77.         /// <returns></returns>  
  78.         public string GetMessage()  
  79.         {  
  80.             using (IConnection conn = rabbitMqFactory.CreateConnection())  
  81.             using (IModel channel = conn.CreateModel())  
  82.             {  
  83.                 BasicGetResult msgResponse = channel.BasicGet(queue: QueueName, noAck: true);  
  84.   
  85.   
  86.                 string msgBody = Encoding.UTF8.GetString(msgResponse.Body);  
  87.   
  88.   
  89.                 return msgBody;  
  90.             }  
  91.         }  
  92.   
  93.   
  94.   
  95.   
  96.         /// <summary>  
  97.         /// 一次都消费光,清空队列,没有消息会阻塞等  
  98.         /// </summary>  
  99.         /// <returns></returns>  
  100.         public string Consume_messages_from_Queue_Subscription()  
  101.         {  
  102.             using (IConnection conn = rabbitMqFactory.CreateConnection())  
  103.             using (IModel channel = conn.CreateModel())  
  104.             {  
  105.                 var consumer = new QueueingBasicConsumer(channel);  
  106.   
  107.   
  108.                 channel.BasicConsume(QueueName, noAck: true, consumer: consumer);  
  109.   
  110.   
  111.                 var msgResponse = consumer.Queue.Dequeue(); //blocking  
  112.   
  113.   
  114.                 var msgBody = Encoding.UTF8.GetString(msgResponse.Body);  
  115.   
  116.   
  117.                 return msgBody;  
  118.             }  
  119.         }  
  120.   
  121.   
  122.   
  123.   
  124.         public void Publish_5_messages_to_test_exchange()  
  125.         {  
  126.             using (IConnection conn = rabbitMqFactory.CreateConnection())  
  127.             using (IModel channel = conn.CreateModel())  
  128.             {  
  129.                 for (var i = 0; i < 5; i++)  
  130.                 {  
  131.                     var props = channel.CreateBasicProperties();  
  132.                     //props.SetPersistent(true);  
  133.                     props.Persistent = true;  
  134.                     string msg = "Hello, World!" + i;  
  135.                     var msgBody = Encoding.UTF8.GetBytes(msg);  
  136.                     channel.BasicPublish(ExchangeName, routingKey: QueueName, basicProperties: props, body: msgBody);  
  137.                 }  
  138.             }  
  139.         }  
  140.   
  141.   
  142.     }  
  143. }  

在main()中往队列插入消息

[csharp]  view plain  copy
  1. static void Main(string[] args)  
  2.         {  
  3.            <span style="white-space:pre"> </span>  //第一次测试  
  4.             MyRabbitMq test = new MyRabbitMq();  
  5.             test.Register_durable_Exchange_and_Queue();  
  6.             test.SendMessage("hahaha"true);            
  7.             //Console.WriteLine(test.GetMessage());  
  8.             //Console.WriteLine(test.Consume_messages_from_Queue_Subscription());  
  9.         }  

运行项目5次,  进入管理界面,可以看到已经创建了一个名叫test.queue 的消息队列,消息Ready标志为5。





后续


这种模式是最简单的P2P模式,还有其他5种模式后面再续。
还要研究如何设置优先级、设置消息ID问题。


参考

http://blog.csdn.net/segen_jaa/article/details/43230431 (安装)
http://www.rabbitmq.com/install-windows.html (官网)
https://github.com/ServiceStack/rabbitmq-windows (producer)
http://www.ibm.com/developerworks/cn/opensource/os-cn-rabbit-mq/   (consumer)

猜你喜欢

转载自blog.csdn.net/xwnxwn/article/details/80459736