.Net Core CAP
2020-08-14 本文已影响0人
谢冰Drama

cap 使用sqlserver 存储本地消息表
rabbitmq 消息发布/订阅
第一步:设置配置信息
/// <summary>
/// 添加cap
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
public static void AddMyCap(this IServiceCollection services, IConfiguration configuration)
{
//保存本地消息记录库的 地址
string capSql = configuration["CAP:connection"];
//消息中间件
string mqUrl = configuration["CAP:MQ:connection"];
services.AddCap(x =>
{
x.UseSqlServer(options =>
{
options.ConnectionString = capSql;
});
//x.UseRabbitMQ(mqUrl);
x.UseRabbitMQ(options =>
{
options.UserName = configuration["CAP:MQ:userName"];
options.HostName = mqUrl;
options.Password = configuration["CAP:MQ:password"];
options.Port = int.Parse(configuration["CAP:MQ:port"] ?? "5672");
});
//x.UseDashboard();
//失败后的重试次数,默认50次;在FailedRetryInterval默认60秒的情况下,即默认重试50*60秒(50分钟)之后放弃失败重试
x.FailedRetryCount = 10;
//失败后的重拾间隔,默认60秒
x.FailedRetryInterval = 60;
});
}
第二步:在StartUp 中的 ConfigService 中
services.AddMyCap(Configuration);
然后就能使用了
使用例子:
/// <summary>
/// cap 测试
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class CapController : ControllerBase
{
private readonly ICapPublisher _capPublisher;
/// <summary>
///
/// </summary>
/// <param name="capPublisher"></param>
public CapController(ICapPublisher capPublisher)
{
_capPublisher = capPublisher;
}
/// <summary>
/// 发布
/// </summary>
/// <returns></returns>
[HttpGet,Route("publish")]
public async Task<string> Publish()
{
await _capPublisher.PublishAsync("bim.core.api", DateTime.Now);
return "发送成功";
}
/// <summary>
/// 订阅
/// </summary>
/// <param name="date"></param>
[SwaggerIgnore(true),HttpGet,Route("receive")]
[CapSubscribe("bim.core.api")]
public void Receive(string date)
{
Console.WriteLine($"接收到订阅:{date}");
}
}
订阅消息 如果是在 controller 中 只需要 贴上 CapSubscribe 特性 即可
如果是写在 service 层, 则 需要实现接口 ICapSubscribe