.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();
        }
    }
相关推荐
沛沛老爹2 分钟前
Web开发者进阶AI:Agent Skills-深度迭代处理架构——从递归函数到智能决策引擎
java·开发语言·人工智能·科技·架构·企业开发·发展趋势
Good_Starry10 分钟前
Java——正则表达式
java·开发语言·正则表达式
二哈喇子!15 分钟前
前端HTML、CSS、JS、VUE 汇总
开发语言·前端
欧洵.18 分钟前
Java.基于UDP协议的核心内容
java·开发语言·udp
情缘晓梦.24 分钟前
C语言数据存储
c语言·开发语言
xunyan623424 分钟前
第九章 JAVA常用类
java·开发语言
IOT-Power33 分钟前
QT 对话框(QDialog)中 accept、reject、exec、open的使用
开发语言·qt
froginwe1135 分钟前
ASP Session
开发语言
lbb 小魔仙42 分钟前
【Python】零基础学 Python 爬虫:从原理到反爬,构建企业级爬虫系统
开发语言·爬虫·python
Swift社区44 分钟前
ArkTS Web 组件里,如何通过 javaScriptProxy 让 JS 同步调用原生方法
开发语言·前端·javascript