RabbitMQ基本使用

1.安装:windows10环境下的RabbitMQ安装步骤(图文)
2
.当RabbitMQ启动成功后
添加发送消息服务(控制台程序):

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

class Send
{
    public static void Main()
    {
        Console.WriteLine("推送消息到RabbitMQ:");
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using(var connection = factory.CreateConnection())
        using(var channel = connection.CreateModel())
        {
            var queueNamme = "test";//队列名
            for (int i = 0; i < 3; i++)
            {
                channel.QueueDeclare(queue: queueNamme, durable: false, exclusive: false, autoDelete: false, arguments: null);

                string message = $"测试一下消息{i}";
                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: "", routingKey: queueNamme, basicProperties: null, body: body);
                Console.WriteLine(" [x] Sent {0}", message);
            }
            
        }

        Console.WriteLine(" Press [enter] to exit.");
        Console.ReadLine();
    }
}

执行后:

 

 可以看到rabbitMQ中消息有3条
然后我们编写一个接收服务程序:

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

class Receive
{
    public static void Main()
    {
        Console.WriteLine("接收消息服务启动:");
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using(var connection = factory.CreateConnection())
        using(var channel = connection.CreateModel())
        {
            var queueName = "test";//队列名
            channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);

            Console.WriteLine(" [*] Waiting for messages.");

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                //接收事件,rabbitmq消息推送给我时,将会触发事件
                var body = ea.Body.ToArray();//推送内容
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            };
            channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
    }
}

启动后:

 

 再次查看rabbitMQ之前的消息已经推送到我们的接收服务里面的消息数就为0了

 

posted @ 2021-02-26 11:27  LBO.net  阅读(107)  评论(0编辑  收藏  举报
//返回顶部