.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();
        }
    }
相关推荐
@西瓜@5 分钟前
JAVAEE(多线程-线程池)
java·开发语言
行思理16 分钟前
go语言应该如何学习
开发语言·学习·golang
q5673152339 分钟前
使用libcurl编写爬虫程序指南
开发语言·c++·爬虫
拓端研究室TRL1 小时前
Python贝叶斯回归、强化学习分析医疗健康数据拟合截断删失数据与参数估计3实例
开发语言·人工智能·python·数据挖掘·回归
しかし1181141 小时前
C语言队列的实现
c语言·开发语言·数据结构·数据库·经验分享·链表
zhangpeng4555479401 小时前
用Java写一个MVCC例子
java·开发语言
point_zg2 小时前
Vue报错...properly without JavaScript enabled. Please enable it to continue
开发语言·javascript·vue
普通网友2 小时前
如何在CentOS部署青龙面板并实现无公网IP远程访问本地面板
开发语言·后端·golang
sa100272 小时前
基于Python的网络爬虫技术研究
开发语言·爬虫·python
API小爬虫2 小时前
如何利用 Java 爬虫获取京东商品详情信息
java·开发语言·爬虫