一聚教程网:一个值得你收藏的教程网站

热门教程

C#操作RabbitMQ的完整实例

时间:2022-06-25 07:48:21 编辑:袖梨 来源:一聚教程网

一、下载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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace Wenli.Data.RabbitMQ.Console
{
  using Console = System.Console;
 
  class Program
  {
    static void Main(string[] args)
    {
      Console.Title = "Wenli.Data.RabbitMQ.Console";
      Console.WriteLine("正连接到mq");
 
      try
      {
        Test();
      }
      catch (Exception ex)
      {
        Console.WriteLine("err:" + ex.Message + ex.Source + ex.StackTrace);
      }
 
      Console.Read();
    }
 
 
    static void Test()
    {
 
      var topic = "testtopic";
 
      var cnn = RabbitMQBuilder.Get(MQConfig.Default).GetConnection();
 
      var operation = cnn.GetOperation(topic);
 
      Console.WriteLine("正连接到订阅【" + topic + "】");
 
      operation.Subscribe();
 
      Console.WriteLine("正在入队");
 
      Task.Factory.StartNew(() =>
      {
        while (true)
        {
          operation.Enqueue(Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "   hello!"));
          Thread.Sleep(1);
        }
      });
 
 
 
 
      Console.WriteLine("正在出队");
 
 
 
      Task.Factory.StartNew(() =>
      {
        while (true)
        {
          var result = operation.Dnqueue();
 
          if (result == null)
          {
            Thread.Sleep(1);
          }
          else
          {
            Console.WriteLine(Encoding.UTF8.GetString(result));
          }
        }
      });
 
      Console.ReadLine();
 
      Console.WriteLine("正在取消订阅");
 
      operation.UnSubscribe();
 
      Console.WriteLine("测试完成");
    }
  }
}

5.运行结果:

至此C# 成功操作Rabbitmq完成。

热门栏目