集成事件
源码及系列文章目录
Git 源码 :https://github.com/tangsong1995/TS.Microservices
CSDN 资源 :https://download.csdn.net/download/qq_33649351/34675095
系列文章目录 :https://blog.csdn.net/qq_33649351/article/details/120998558
集成事件的工作原理
集成事件的目的是为了实现系统集成。用于系统内多个微服务间传递事件。
集成事件的实现方式有两种,一种是通过 Event Bus 发布订阅的方式实现,一种是通过观察者模式实现。本文实现的是 Event Bus 的方式。
集成事件的实现
.Net开源社区提供了 DotNetCore.CAP 框架,借助 CAP 框架,可以很轻松的实现消息的发布和订阅。
CAP框架
CAP框架:CAP 。
CAP框架实现了OutBox的设计模式:在每个微服务的数据库内部建立两张表:publish事件表和receive事件表。publish事件表用于存储微服务发出的集成事件,receive事件表用于存储微服务接收到的集成事件。发布集成事件时,CAP会把事件的存储逻辑和业务逻辑绑定在一起,在同一事务提交,保证业务数据修改与集成事件消息发布的一致性。
使用CAP实现消息的发布
发布端定义领域事件,借助 ICapPublisher 对象的 PublishAsync 方法将集成事件发送出去:
public class OrderCreatedDomainEventHandler : IDomainEventHandler<OrderCreatedDomainEvent>
{
ICapPublisher _capPublisher;
public OrderCreatedDomainEventHandler(ICapPublisher capPublisher)
{
_capPublisher = capPublisher;
}
public async Task Handle(OrderCreatedDomainEvent notification, CancellationToken cancellationToken)
{
// OrderCreated 事件名称
await _capPublisher.PublishAsync("OrderCreated", new OrderCreatedIntegrationEvent(notification.Order.Id));
}
}
使用CAP实现消息的订阅
定义订阅服务接口:
public interface ISubscriberService
{
void OrderPaymentSucceeded(OrderPaymentSucceededIntegrationEvent @event);
void OrderCreated(OrderCreatedIntegrationEvent @event);
}
通过继承CAP的 ICapSubscribe 接口,给方法打上 CapSubscribe 标签,并传入订阅的事件名,实现消息的订阅:
public class SubscriberService : ISubscriberService, ICapSubscribe
{
IMediator _mediator;
public SubscriberService(IMediator mediator)
{
_mediator = mediator;
}
[CapSubscribe("OrderPaymentSucceeded")]
public void OrderPaymentSucceeded(OrderPaymentSucceededIntegrationEvent @event)
{
//Do SomeThing
}
[CapSubscribe("OrderCreated")]
public void OrderCreated(OrderCreatedIntegrationEvent @event)
{
//Do SomeThing
}
}
OrderCreatedIntegrationEvent 集成事件发布订阅参数模型:
public class OrderCreatedIntegrationEvent
{
public OrderCreatedIntegrationEvent(long orderId) => OrderId = orderId;
public long OrderId { get; }
}
使用 CAP + RabbitMQ 实现集成事件
RabbitMQ下载及安装请参考: RabbitMQ下载及安装 、 RabbitMQ安装教程 。
保障业务数据变更和集成事件消息发布的一致性
在 EFContext 中 BeginTransactionAsync 方法中定义入参 ICapPublisher ,保障业务数据变更和集成事件消息发布在同一事物内。这里不能直接使用构造函数注入,因为 ICapPublisher 也会使用到 DbContext :
public class EFContext : DbContext, IUnitOfWork, ITransaction
{
protected IMediator _mediator;
public EFContext(DbContextOptions options, IMediator mediator) : base(options)
{
_mediator = mediator;
}
...
public Task<IDbContextTransaction> BeginTransactionAsync(ICapPublisher capBus)
{
if (_currentTransaction != null) return null;
_currentTransaction = Database.BeginTransaction(capBus, autoCommit: false);
return Task.Fromresult(_currentTransaction);
}
...
}
CAP配置
定义 AddEventBus ,注入订阅服务,并且配置 Cap :针对 OrderingContext 实现 EventBus (共享数据库连接),指定使用 RabbitMQ 作为 EventBus 的消息队列的存储:
public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
{
services.AddTransient<ISubscriberService, SubscriberService>();
services.AddCap(options =>
{
options.UseEntityFramework<OrderingContext>();
options.UseRabbitMQ(options =>
{
configuration.GetSection("RabbitMQ").Bind(options);
});
// 失败重试
options.FailedRetryCount = 5;
options.FailedThresholdCallback = Failed =>
{
var logger = Failed.ServiceProvider.GetService<ILogger<Startup>>();
logger.LogError($@"A message of type {Failed.MessageType} Failed after executing {options.FailedRetryCount} several times,
requiring manual troubleshooting. Message name: {Failed.Message.GetName()}");
};
//options.UseDashboard();
});
return services;
}
RabbitMQ 配置:
"RabbitMQ": {
"HostName": "localhost",
"UserName": "guest",
"Password": "guest",
"VirtualHost": "ts",
"ExchangeName": "ts_queue"
}
Startup 下的 ConfigureServices 方法中添加 EventBus :
public void ConfigureServices(IServiceCollection services)
{
services.AddEventBus(Configuration);
}
启动服务可以看到RabbitMQ已连接:
并且有两个Routekey:
实现集成事件注意点
- 集成事件一般由领域事件驱动触发。
- 一般不通过事务来处理集成事件,实现最终一致性即可,对数据有强一致性的事件除外。
- 仅在必要的情况下定义和使用集成事件,集成事件在更新版本时需要做新旧版本的兼容处理。
原文地址:https://www.jb51.cc/wenti/3284764.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。