zoukankan      html  css  js  c++  java
  • 在ABP代码项目中使用CAP进行分布式事务处理

    先准备好一个ABP模板代码解决方案,按DotnetCore.CAP的使用教程。

    代码跑起

    abp的windsor castle DI 容器,并没有注入DbContext的实例,这是必然的,ABP 的Dbcontext是靠 addabp() 注入到 DI 容器中。因此想要向ServiceCollection注入CAP服务,并且还期望使用EF,在ABP框架中并不支持。这是注入的一个先后问题,因为addcap()成功的前提是必须在ServiceProvider中能够把 DbContext的实例反射拿到手。

    且看CAP的源码

     那么该咋办呢?

    可以直接引用数据库连接字符串,这样就不须dbcontext实例了。

    接下来,是事务的处理了。

    按CAP教程是这样的,给了一个ado.net,一个EF的例子。

    https://github.com/dotnetcore/CAP

    既然EF是用不了了,那就尝试用dapper。

    https://aspnetboilerplate.com/Pages/Documents/Dapper-Integration

     定义了一个dappermodule, 在ABP的application应用层模块中注入了这个模块。

    public class SomeApplicationService : ITransientDependency
    {
        private readonly IDapperRepository<Person> _personDapperRepository;
        private readonly IRepository<Person> _personRepository;
    
        public SomeApplicationService(
            IRepository<Person> personRepository,
            IDapperRepository<Person> personDapperRepository,
             ICapPublisher capPublisher)
        {
            _personRepository = personRepository;
            _personDapperRepository = personDapperRepository;
             _capBus = capPublishe; 
        }
    
        public void DoSomeStuff()
        {
            var people = _personDapperRepository.Query("select * from Persons");
             await _capBus.PublishAsync("othersystem.aftergetperson", input);
        }
    }

     因为在ABP的applicationservice中的方法,默认是自带unitofwork的,所以代码中无须再用事务代码块。

    总结:在使用CAP的时候,最开始的目标是想着分布式事务能够支持自动回滚,也就是在本服务中,跨服务调用失败,本服务的操作能够回滚。但经过一番了解,这只是我的一厢情愿,真的要达到这个目标,代价肯定是昂贵的。CAP只是基于事务补偿的思路,即本服务中,跨服务调用失败,本服务中的操作不会自动回滚,而是通过消息队列去尝试跨服务操作的补偿,最终达到操作数据的完整性。

  • 相关阅读:
    selenium实战
    selenium+unittest实现po模型
    IDE自动化脚本实现
    web 自动化测试
    requests 遇到报错UnicodeEncodeError: 'latin-1' codec can't encode character 'u86c7' in position 8: Body ('蛇') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
    通过requests + pytest + allure 实现接口自动化测试
    python pytest单元测试
    python unittest单元测试
    laili和网路知识
    网络-单臂路由
  • 原文地址:https://www.cnblogs.com/wikiz/p/11115894.html
Copyright © 2011-2022 走看看