在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只是基於事務補償的思路,即本服務中,跨服務調用失敗,本服務中的操作不會自動回滾,而是通過消息隊列去嘗試跨服務操作的補償,最終達到操作數據的完整性。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM