1. 安装RabbitMQ

详情参考:

【RabbitMQ】超详细Windows系统下RabbitMQ的安装配置_rabbitmq安装 win系统-CSDN博客 

2. appsettings.json 设置

  "RabbitMQ": {
    "HostName": "localhost",
    "Port": 5672,
    "UserName": "guest",
    "Password": "guest",
    "VirtualHost": "/"
  },

3. 代码实现 

using Newtonsoft.Json;
using RabbitMQ.Client;
using System.Text;

namespace Demo.Services
{
    //Program.cs regiter service in below
    //builder.Services.AddSingleton<IMessagePublish, MessagePublish>();

    public interface IMessagePublish
    {
        void PublishMessage<T>(string QueueName, T t);
    }

    public class MessagePublish : IMessagePublish
    {
        private readonly IModel channel;
        private readonly IConfiguration _configuration;

        public MessagePublish(IConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.HostName = _configuration["RabbitMQ:HostName"];
            if (int.TryParse(_configuration["RabbitMQ:Port"], out var port))
            {
                connectionFactory.Port = port;
            }
            connectionFactory.UserName = _configuration["RabbitMQ:UserName"];
            connectionFactory.Password = _configuration["RabbitMQ:Password"];
            connectionFactory.VirtualHost = _configuration["RabbitMQ:VirtualHost"];
            IConnection connection = connectionFactory.CreateConnection();

            channel = connection.CreateModel();
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        public void PublishMessage<T>(string routingKey, T t)
        {
            if (routingKey.Length > 255)
            {
                throw new ArgumentOutOfRangeException(nameof(routingKey), $"routingKey limitation is 255 bytes");
            }
            channel.QueueDeclare(routingKey, false, false, false);
            string productJson = JsonConvert.SerializeObject(t);
            byte[] productByte = Encoding.UTF8.GetBytes(productJson);
            channel.BasicPublish("",
                                routingKey,
                                 true,
                                 channel.CreateBasicProperties(),
                                  productByte);
        }
    }

}

4. 利用DI注册

//Program.cs register service in below
builder.Services.AddSingleton<IMessagePublish, MessagePublish>();

5. 引用Demo

    [ApiController]
    [Route("[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly IMessagePublish _messagePublish;

        public ProductController(IMessagePublish messagePublish)
        {
            _messagePublish = messagePublish;
        }

        /// <summary>
        /// AddProduct
        /// </summary>
        /// <returns></returns>

        [HttpPost(Name = "AddProduct")]
        public IActionResult AddProduct(Product product)
        {
            _messagePublish.PublishMessage("AddProduct", product);

            return Ok();
        }
    }

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部