前言:

本篇介绍官方提供的SDK:Rabbit.Client的简单使用,本篇尽量使用最简代码,以便初学者能快速理解与掌握。

1、项目中Nuget引入Rabbit.Client:

 

2、创建链接:(用户名密码自行调整)

using RabbitMQ.Client;

var factory = new ConnectionFactory()
{
    HostName = "127.0.0.1",
    UserName = "guest",
    Password = "guest",
    VirtualHost = "/"
};

var connection = factory.CreateConnection();

如果是Web应用中使用,这里需要把它改造成单例使用。

3、单例改造:

class Rabbit
{
    ConnectionFactory factory;
    private Rabbit()
    {
        factory = new ConnectionFactory()
        {
            HostName = "127.0.0.1",
            UserName = "guest",
            Password = "guest",
            VirtualHost = "/"
        };
    }
    private IConnection _Connection;
    public IConnection DefaultConnection
    {
        get
        {
            if (_Connection == null)
            {
                _Connection = factory.CreateConnection();
            }
            return _Connection;
        }
    }
    public static Rabbit Instance = new Rabbit();
}

4、发送消息:(创建FirstQueue队列)

using RabbitMQ.Client;
using System.Text;

using (var channel = Rabbit.Instance.DefaultConnection.CreateModel())
{
    channel.QueueDeclare("FirstQueue", false, false, false);
    channel.BasicPublish("", "FirstQueue", false, null, Encoding.UTF8.GetBytes("这是要发送的内容"));
}

5、发送消息:批量发送

using (var channel = Rabbit.Instance.DefaultConnection.CreateModel())
{
    channel.QueueDeclare("FirstQueue", false, false, false);
    //channel.BasicPublish("", "FirstQueue", false, null, Encoding.UTF8.GetBytes("这是要发送的内容"));
    var pub= channel.CreateBasicPublishBatch();
    pub.Add("", "FirstQueue", false, null, Encoding.UTF8.GetBytes("这是批量要发送的内容1"));
    pub.Add("", "FirstQueue", false, null, Encoding.UTF8.GetBytes("这是批量要发送的内容2"));
    pub.Add("", "FirstQueue", false, null, Encoding.UTF8.GetBytes("这是批量要发送的内容3"));
    pub.Publish();
}

6、接收消息:(接收消息要保持通道一直开,所以不能关闭)

using RabbitMQ.Client;
using System.Text;

var channel = Rabbit.Instance.DefaultConnection.CreateModel();

var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
    var message = Encoding.UTF8.GetString(ea.Body.ToArray());
    Console.WriteLine("收到默认消息 {0}", message);
};
channel.BasicConsume("FirstQueue",true,consumer);

 

 

总结:

本篇介绍RabbitMQ最简代码的使用,方便入门与理解。

posted on 2022-08-22 11:31  路过秋天  阅读(1823)  评论(3编辑  收藏  举报
路过秋天