.Net Core 微服务实战 - 集成事件

源码及系列文章目录

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实现架构
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:
在这里插入图片描述

触发集成事件后也会在数据库生成相应的记录:
在这里插入图片描述
在这里插入图片描述

实现集成事件注意点

  • 集成事件一般由领域事件驱动触发。
  • 一般不通过事务来处理集成事件,实现最终一致性即可,对数据有强一致性的事件除外。
  • 仅在必要的情况下定义和使用集成事件,集成事件在更新版本时需要做新旧版本的兼容处理。
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值