C#操作RabbitMQ的完整实例

一、下载RabbitMQ http: www rabbitmq com install-windows html二、下载OTP http: www erla

一、下载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.测试代码:

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完成。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好代码网。

标签: C RabbitMQ