.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 小时前
C# 扩展方法只会写 this 吗?C# 14 新语法直接把扩展方法玩出了花
c#
唐青枫4 小时前
C#.NET SignalR 深入解析:实时通信、Hub 与连接管理实战
c#·.net
唐宋元明清21889 小时前
.NET Win32磁盘动态卷/跨区卷触发“函数不正确”问题排查
windows·c#·存储
hez201010 小时前
Satori GC:同时做到高吞吐、低延时和低内存占用
c#·.net·.net core·gc·clr
牧马人win1 天前
.NET 开发 MCP 服务器完全指南:打造智能数据库查询助手
ai·.net·mcp
唐青枫1 天前
C#.NET Channel 深入解析:高性能异步生产者消费者模型实战
c#·.net
小峥降临2 天前
Rokid UXR 的手势追踪虚拟中更真实的手实战开发【含 工程源码 和 最终完成APK】
c#
国思RDIF框架5 天前
RDIFramework.NET CS 敏捷开发框架 V6.3 版本重磅发布!.NET8+Framework双引擎,性能升级全维度进化
后端·.net