一个C#操作RabbitMQ的完整例子
一、下载RabbitMQ
http://www.rabbitmq.com/install-windows.html
二、下载OTP
http://www.erlang.org/downloads
三、安装OTP、RabbitMQ
四、配置RabbitMQ
找到bat的目录
执行相关命令
1.添加用户密码 rabbitmqctl add_user wenli wenli
2.设置wenli为管理员 rabbitmqctl set_user_tags wenli administrator
3.启动RabbitMQ的web管理 rabbitmq-plugins enable rabbitmq_management
4.创建virtual host
5.设置用户权限
点击用户名进行设置
将virtual hosts 权限赋给用户wenli
6.创建Exchanges
五.创建C# console
1.下载RabbitMQ驱动 https://github.com/yswenli/Wenli.Data.RabbitMQ/releases/tag/Release1.0.0
2.添加引用
3.添加配置
4.测试代码:
1 using System; 2 using System.Text; 3 using System.Threading; 4 using System.Threading.Tasks; 5 6 namespace Wenli.Data.RabbitMQ.Console 7 { 8 using Console = System.Console; 9 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 Console.Title = "Wenli.Data.RabbitMQ.Console"; 15 Console.WriteLine("正连接到mq"); 16 17 try 18 { 19 Test(); 20 } 21 catch (Exception ex) 22 { 23 Console.WriteLine("err:" + ex.Message + ex.Source + ex.StackTrace); 24 } 25 26 Console.Read(); 27 } 28 29 30 static void Test() 31 { 32 33 var topic = "testtopic"; 34 35 var cnn = RabbitMQBuilder.Get(MQConfig.Default).GetConnection(); 36 37 var operation = cnn.GetOperation(topic); 38 39 Console.WriteLine("正连接到订阅【" + topic + "】"); 40 41 operation.Subscribe(); 42 43 Console.WriteLine("正在入队"); 44 45 Task.Factory.StartNew(() => 46 { 47 while (true) 48 { 49 operation.Enqueue(Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " hello!")); 50 Thread.Sleep(1); 51 } 52 }); 53 54 55 56 57 Console.WriteLine("正在出队"); 58 59 60 61 Task.Factory.StartNew(() => 62 { 63 while (true) 64 { 65 var result = operation.Dnqueue(); 66 67 if (result == null) 68 { 69 Thread.Sleep(1); 70 } 71 else 72 { 73 Console.WriteLine(Encoding.UTF8.GetString(result)); 74 } 75 } 76 }); 77 78 Console.ReadLine(); 79 80 Console.WriteLine("正在取消订阅"); 81 82 operation.UnSubscribe(); 83 84 Console.WriteLine("测试完成"); 85 } 86 } 87 }
5.运行结果:
至此C# 成功操作Rabbitmq完成
转载请标明本文来源:http://www.cnblogs.com/yswenli/p/7446919.html
更多内容欢迎star作者的github:https://github.com/yswenli/Wenli.Data.RabbitMQ
如果发现本文有什么问题和任何建议,也随时欢迎交流~