龙空技术网

.net6 中使用 RabbitMQ

晓川头条 109

前言:

今天同学们对“rabbitmqnet”大体比较关切,朋友们都想要剖析一些“rabbitmqnet”的相关文章。那么小编同时在网上收集了一些对于“rabbitmqnet””的相关内容,希望我们能喜欢,看官们一起来学习一下吧!

1. 安装 NuGet 包

dotnet add package RabbitMQ.Client
2. 创建连接和通道
using RabbitMQ.Client;// 创建连接和通道var factory = new ConnectionFactory(){    HostName = "localhost",    UserName = "guest",    Password = "guest"};using var connection = factory.CreateConnection();using var channel = connection.CreateModel();
3. 发送消息
// 声明通道channel.QueueDeclare("my_queue", false, false, false, null);// 发送消息var body = Encoding.UTF8.GetBytes("我是一条消息");channel.BasicPublish("", "my_queue", null, body);
4. 接收消息
using RabbitMQ.Client;using RabbitMQ.Client.Events;using System.Text;// 创建连接和通道var factory = new ConnectionFactory(){    HostName = "localhost",    UserName = "guest",    Password = "guest"};using var connection = factory.CreateConnection();using var channel = connection.CreateModel();var consumer = new EventingBasicConsumer(channel);consumer.Received += (model, ea) =>{    var body = ea.Body.ToArray();    var message = Encoding.UTF8.GetString(body);    Console.WriteLine("Received: {0}", message);};channel.BasicConsume(queue: "my_queue", autoAck: true, consumer: consumer);Console.ReadKey();
5. Work消息模型6. 订阅模型6.1 定义 RabbitMqConfig 类
namespace Producer{    public class RabbitMqConfig    {        public string HostName { get; set; }        public string QueueName { get; set; }        public string RoutingKey { get; set; }        public string ExchangeName { get; set; }        public string ExchangeType { get; set; }        public string Username { get; set; }        public string Password { get; set; }    }    public class Payload    {        public string Message { get; set; }    }}
6.2 定义创建者类
using Microsoft.Extensions.Options;using RabbitMQ.Client;using System.Text;using System.Text.Json;namespace Producer{    public interface IRabbitMqSender    {        void SendMessage(string message);    }    public class RabbitMqSender : IRabbitMqSender    {        private readonly string queueName;        private readonly string exchangeName;        private readonly IConnection connection;        private readonly IModel channel;        public RabbitMqSender(IOptions<RabbitMqConfig> cfg)        {            var factory = new ConnectionFactory            {                HostName = cfg.Value.HostName,                UserName = cfg.Value.Username,                Password = cfg.Value.Password            };            queueName = cfg.Value.QueueName ?? string.Empty;            exchangeName = cfg.Value.ExchangeName ?? string.Empty;            connection = factory.CreateConnection();            channel = connection.CreateModel();            // 声明队列            channel.QueueDeclare(                // 队列的名称。如果未定义,代理将生成一个。                queue: queueName,                // 如果启用,代理在重新启动时不会删除队列。                durable: false,                // 如果启用,队列将仅由一个连接使用,并在连接关闭时删除。                exclusive: false,                // 如果启用,当队列不再使用时,服务器将删除它。                autoDelete: false,                arguments: null);            if (!string.IsNullOrWhiteSpace(cfg.Value.ExchangeType))            {                // 声明交换机                channel.ExchangeDeclare(                    exchange: exchangeName,                    type: cfg.Value.ExchangeType);                // 交换机与队列绑定                channel.QueueBind(queueName, exchangeName, cfg.Value.RoutingKey);            }        }        public void SendMessage(string message)        {            var payload = new Payload() { Message = message };            var properties = channel.CreateBasicProperties();            properties.Persistent = true;            var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload));            channel.BasicPublish(exchange: exchangeName, routingKey: queueName, basicProperties: properties, body: body);        }        ~RabbitMqSender()        {            if (connection is not null)            {                channel.Close();                connection.Close();                channel.Dispose();                connection.Dispose();            }        }    }}
6.3 如何调用
using Microsoft.Extensions.Options;using Producer;// 基本消息类型new RabbitMqSender(Options.Create(new RabbitMqConfig{    HostName = "localhost",    Username = "guest",    Password = "guest",    QueueName = "my_queue"})).SendMessage("我是一条普通消息");// 订阅模型// Directnew RabbitMqSender(Options.Create(new RabbitMqConfig{    HostName = "localhost",    Username = "guest",    Password = "guest",    QueueName = "my_queue",    ExchangeName = "my_direct_exchange",    ExchangeType = "direct",    RoutingKey = "my_routing"})).SendMessage("我是一条Direct消息");// Topicnew RabbitMqSender(Options.Create(new RabbitMqConfig{    HostName = "localhost",    Username = "guest",    Password = "guest",    ExchangeName = "my_topic_exchange",    ExchangeType = "topic",    RoutingKey = "my_routing.*",    QueueName = "my_routing.one"})).SendMessage("我是一条Topic消息");// Fanoutnew RabbitMqSender(Options.Create(new RabbitMqConfig{    HostName = "localhost",    Username = "guest",    Password = "guest",    ExchangeName = "my_fanout_exchange",    ExchangeType = "fanout",    RoutingKey = "my_routing.*"})).SendMessage("我是一条Fanout消息");
7. windows 下安装 RabbitMQ

windows 下安装 RabbitMQ

标签: #rabbitmqnet