.NET 8 API + RabbitMQ demo

  1. 安装RabbitMQ

详情参考:

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

  1. appsettings.json 设置
XML 复制代码
  "RabbitMQ": {
    "HostName": "localhost",
    "Port": 5672,
    "UserName": "guest",
    "Password": "guest",
    "VirtualHost": "/"
  },
  1. 代码实现
cs 复制代码
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);
        }
    }

}
  1. 利用DI注册
cs 复制代码
//Program.cs register service in below
builder.Services.AddSingleton<IMessagePublish, MessagePublish>();
  1. 引用Demo
cs 复制代码
    [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();
        }
    }
相关推荐
喵手1 小时前
Java 与 Oracle 数据泵实操:数据导入导出的全方位指南
java·开发语言·oracle
硬汉嵌入式2 小时前
H7-TOOL的LUA小程序教程第16期:脉冲测量,4路PWM,多路GPIO和波形打印(2024-10-25, 更新完毕)
开发语言·junit·小程序·lua
小小娥子2 小时前
rabbitmq高级特性(1):消息确认,持久性,发送方确认和重试机制
分布式·rabbitmq
XQ_8988788882 小时前
【04】RabbitMQ的集群机制
rabbitmq
Wx120不知道取啥名2 小时前
C语言之长整型有符号数与短整型有符号数转换
c语言·开发语言·单片机·mcu·算法·1024程序员节
Python私教3 小时前
Flutter颜色和主题
开发语言·javascript·flutter
代码吐槽菌3 小时前
基于SSM的汽车客运站管理系统【附源码】
java·开发语言·数据库·spring boot·后端·汽车
Ws_3 小时前
蓝桥杯 python day01 第一题
开发语言·python·蓝桥杯
zdkdchao3 小时前
jdk,openjdk,oraclejdk
java·开发语言
神雕大侠mu4 小时前
函数式接口与回调函数实践
开发语言·python