1.简单几行代码实现事件总线
// 添加事件总线cap
services.AddCap(x => {
// 使用内存存储消息(消息发送失败处理)
// x.UseInMemoryStorage();
// 使用EntityFramework进行存储操作
x.UseEntityFramework<AggregateContext>();
// 使用sqlserver进行事务处理,防止推送MQ失败,会在指定数据库中自动生成以"cap."开头的表
x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
// 使用RabbitMQ进行事件中心处理
x.UseRabbitMQ(rb => {
rb.HostName = "localhost";
rb.UserName = "admin";
rb.Password = "admin";
rb.Port = 5672;
rb.VirtualHost = "/";
});
// 添加cap后台监控页面(人工处理);页面地址为“/cap”
x.UseDashboard();
// 配置定时器重试策略
//x.FailedRetryInterval = 2; //重试间隔时间(秒),使用默认的就可以,可不用配置
x.FailedRetryCount = 5; //重试次数
});
// 注册上下文到IOC容器
services.AddDbContext<AggregateContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
2.事件发布
[Route("api/Teams")]
[ApiController]
public class AggregateController : ControllerBase
{
private readonly ICapPublisher capPublisher;
public AggregateController(ICapPublisher capPublisher)
{
this.capPublisher = capPublisher;
}
/// <summary>
/// 添加团队和成员信息
/// </summary>
/// <param name="value"></param>
[HttpPost]
public ActionResult Post(string value)
{
Video video = new Video()
{
VideoUrl = "http://localhost:5365/123.mp4",
MemberId =1
};
capPublisher.PublishAsync<Video>("video.event.post", video);
return Ok("添加成功");
}
}
3.事件订阅
[Route("Video")]
[ApiController]
public class VideoController : ControllerBase
{
private readonly IVideoService videoService;
public VideoController(IVideoService videoService)
{
this.videoService = videoService;
}
/// <summary>
/// 视频添加
/// </summary>
/// <param name="Video"></param>
/// <returns></returns>
[NonAction] //用于标识此函数不是接口,将不能被http请求访问
//[CapSubscribe("video.event.*")] // * 一对多匹配 # 一对一匹配
[CapSubscribe("video.event.post")]
public ActionResult<Video> PostVideo(Video Video)
{
videoService.Create(Video);
return CreatedAtAction("GetVideo", new { id = Video.Id }, Video);
}
}
转载:.Net Core 使用CAP框架实现异步化分布式事务_熊大哈的博客-CSDN博客
相关文章:
.NetCore Cap 结合 RabbitMQ 实现消息订阅 - osc_jbyqrnfz的个人空间 - OSCHINA - 中文开源技术交流社区