RabbitMQ
RabbitMQ
1.安装nget包
DotNetCore.CAP
2.在program里写配置
//加入CAP
builder.Services.AddCap(x =>
{
//读取上下文
x.UseEntityFramework<MemberContext>(); // EF
//读取数据库
x.UseSqlServer(builder.Configuration["ConnectionStrings:Serve"]); // SQL Server
//注入相关配置
x.UseRabbitMQ(cfg =>
{
//主机
cfg.HostName = builder.Configuration["RabbitMQ:Host"];
//虚拟主机
cfg.VirtualHost = builder.Configuration["RabbitMQ:VirtualHost"];
//端口
cfg.Port = Convert.ToInt32(builder.Configuration["RabbitMQ:Port"]);
//用户名
cfg.UserName = builder.Configuration["RabbitMQ:UserName"];
//密码
cfg.Password = builder.Configuration["RabbitMQ:Password"];
}); // RabbitMQ
// Below settings is just for demo
//失败重试次数
x.FailedRetryCount = 2;
//每次间隔5秒
x.FailedRetryInterval = 5;
});
3.在appsettings配置文件里写入上面的连接条件
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
//连接字符串
"ConnectionStrings": { "Serve": "Data Source=10.31.60.17;Encrypt=True;Initial Catalog=MemberDB;TrustServerCertificate=True;uid=wzy;pwd=123456" },
//MQ相关配置
"RabbitMQ": {
"Host": "127.0.0.1", //主机
"VirtualHost": "/",//虚拟主机
"Port": 5672,//端口
"UserName": "guest", //RabbitMQ的账户名
"Password": "guest" //RabbitMQ的密码
}
}
4.生产者:发布消息
/// <summary>
/// 获取会员等级
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult GetMemberLevelTable([FromServices] ICapPublisher capBus)
{
var list = levelBenefits.GetMemberLevelTable();
capBus.Publish("GetMemberLevelTable", list);
var MaxNumber = 0;
if (list.Count!=0)
{
MaxNumber = list.Max(x => x.MemberLevel_Id);
}
return Ok(new { list, MaxNumber });
}
5.消费者:接收消息
/// <summary>
/// 获取mq
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[HttpGet]
[CapSubscribe("GetMemberLevelTable")]
[Route("MQShow")]
public IActionResult MQShow(List<object> obj)
{
return Ok(obj);
}