- 安装RabbitMQ
详情参考:
【RabbitMQ】超详细Windows系统下RabbitMQ的安装配置_rabbitmq安装 win系统-CSDN博客
- appsettings.json 设置
XML
"RabbitMQ": {
"HostName": "localhost",
"Port": 5672,
"UserName": "guest",
"Password": "guest",
"VirtualHost": "/"
},
- 代码实现
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);
}
}
}
- 利用DI注册
cs
//Program.cs register service in below
builder.Services.AddSingleton<IMessagePublish, MessagePublish>();
- 引用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();
}
}