一、webForm项目中发布
1、引用RabbitMQ.Client
2、在你想要发布的地方调用如下的方法
public void PublishRabbitMQ()
{
var data = new { ProductId = Guid.NewGuid(), NewCount = 10};
try
{
var factory = new RabbitMQ.Client.ConnectionFactory();
factory.HostName = "xxx.xxx.xxx.xxx";
factory.UserName = "root";
factory.Password = "123456";
factory.Port = 5672;
factory.VirtualHost = "/";
using (var connection = factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
channel.QueueDeclare(Convert.ToString("master-queue"), true, false, false, null);
IBasicProperties properties = channel.CreateBasicProperties();
properties.Persistent = true;
properties.DeliveryMode = 2;
properties.Expiration = "172800000";//48小时过期
string da = Newtonsoft.Json.JsonConvert.SerializeObject(data).Replace("\r\n", "");
channel.BasicPublish(
exchange: "xxxUpdate",
routingKey: Convert.ToString("xxx.Product.StockChange"),
mandatory: true,
basicProperties: properties,
body: Encoding.UTF8.GetBytes(da));
}
}
}
catch (Exception ex)
{
}
}
二、ABP Vnext项目中订阅
1、appsettings.json文件中配置,注意此处的ExchangeName要与webForm项目中的相同
"RabbitMQ": {
"Connections": {
"Default": {
"HostName": "xxx.xxx.xxx.xxx",
"Port": "5672",
"UserName": "root",
"Password": "123456",
"VirtualHost": "/"
}
},
"EventBus": {
"ClientName": "xxxUpdate_baseInfoService",
"ExchangeName": "xxxUpdate"
}
}
2、在调用的项目中引用Nuget包
3、在项目中依赖模块 [DependsOn(typeof(AbpEventBusRabbitMqModule))]
4、订阅事件
[EventName("xxx.Product.StockChange")]
public class StockCountChangedEto
{
public Guid ProductId { get; set; }
public int NewCount { get; set; }
}
public class MyHandler
: IDistributedEventHandler<StockCountChangedEto>,
ITransientDependency
{
public async Task HandleEventAsync(StockCountChangedEto eventData)
{
var productId = eventData.ProductId;
}
}