c# rabbitMQ简单收发消息

C# rabbitMQ简单收发消息的使用

1、创建两个控制台应用程序,项目结构如下:
c# rabbitMQ简单收发消息_第1张图片
2、引入rabbitMQ程序包c# rabbitMQ简单收发消息_第2张图片
c# rabbitMQ简单收发消息_第3张图片
c# rabbitMQ简单收发消息_第4张图片
回车之后,稍等片刻,rabbitMQ程序包就会安装好。

3、主要代码

3.1 发送消息

using System;
using System.Text;
using RabbitMQ.Client;

namespace Sender
{
    class Program
    {
        static void Main(string[] args)
        {
            // 连接工程类,可以创建IConnection
            ConnectionFactory factory = new ConnectionFactory()
            {
                HostName = "localhost",
                UserName = "guest",
                Password = "guest",
                Port = 5672
            };
            // 连接对象
            IConnection connection = factory.CreateConnection();
            // 传输消息的信道
            IModel channel = connection.CreateModel();
            // 声明一个Test队列
            channel.QueueDeclare("Test", false, false, false, null);
            // 传输的消息
            string message = "你好,世界";
            // 指定字符串中的所有字符编码为一个字节序列
            var body = Encoding.UTF8.GetBytes(message);
            // 往Test队列中发送消息
            channel.BasicPublish("", "Test", null, body); 
            Console.WriteLine("已发送: {0}", message);
            // 关闭信道
            channel.Close();
            // 关闭连接
            connection.Close();
            Console.ReadLine();
        }
    }
}

3.2、接收消息

using System;
using System.Text;

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace Receiver
{
    class Program
    {
        static void Main(string[] args)
        {
            ConnectionFactory factory = new ConnectionFactory()
            {
                HostName = "localhost",
                UserName = "guest",
                Password = "guest",
                Port = 5672
            };
            IConnection connection = factory.CreateConnection();
            IModel channel = connection.CreateModel();
            channel.QueueDeclare("Test", false, false, false, null);
            var consumer = new EventingBasicConsumer(channel);
            channel.BasicConsume("Test", false, consumer);
            consumer.Received += OnDataReceived;
            Console.ReadLine();
        }

        public static void OnDataReceived(object sender, BasicDeliverEventArgs e)
        {
            var body = e.Body;
            var message = Encoding.UTF8.GetString(body);
            Console.WriteLine("已接收: {0}", message);
        }
    }
}

4、运行结果
在这里插入图片描述
c# rabbitMQ简单收发消息_第5张图片
rabbitMQ管理界面
c# rabbitMQ简单收发消息_第6张图片

你可能感兴趣的:(RabbitMQ)