AbpVnext 分布式事件总线
作者:互联网
AbpVnext 本地事件总线
补充知识
发布订阅
概念
应用场景
本地事件总线允许服务发布和订阅进程内事件,这意味着如果两个服务>(发布者和订阅者)在同一个进程中运行,那么它是合适的
完整示例
DDD开发规范: 先定义好接口层、后实现层、暴露接口
对于要更新的实体
//领域层的实体
public class Book : FullAuditedEntity<Guid>, IHasExtraProperties, IMultiTenant
{
public string Name{get;set;}
public string Author {get;set;}
public long Price {get;set}
public string Title {get;set;}
public string Classify{get;set;}
//条形码
public string BarCode {get;set;}
// 出版商
public string Issue{get;set;}
// 页数
public string PageTotal{get;set;}
public string BuyerId{get;set;}
public DateTime? ModifyTime{get;set}
}
//这个实体是必须有的
public class BookRecordEto{
public string Name{get;set;}
public string Author {get;set;}
public long Price {get;set}
public DateTime? ModifyTime{get;set}
}
//发布事件
public class BookService: ITransientDependency
{
//Abp使用了字典来保存对实例的引用
public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
//按需注入
protected ILocalEventBus LocalEventBus => LazyServiceProvider.LazyGetRequiredService<ILocalEventBus >();
//仓储--对应Book的数据库表
protected IBookRepository BookRepository => LazyGetRequiredService<IBookRepository>();
public async Task UpdateData(Guid id)
{
var book = await BookRepository.FindAsync(x=>x.Id = id);
if (book == null){//不存在实体}
var updateEntity = await BookRepository.UpdateAsync(book);
if (updateEntity == null){//更新失败}
//实体数据发生变更,发布事件
await LocalEventBus.PublishAsync(new BookEto(){
Name = book.Name;
Author = book.Author;
Price = book.Price;
ModifyTime = DateTime.Now;
});
}
}
//订阅事件
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus;
public class EventBusHandler: ApplicationService,
, ILocalEventHandler<BookRecordEto>
, ITransientDependency
{
// 进行业务数据更新,比如要更新购买这边书读者记录
public IAbpLazyServiceProvider LazyServiceProvider{get;set;}
protected IBookBoughtRecordRepository BoughtRecordRepository => LazyServiceProvider.LazyGetRequiredService<IBookBoughtRecordRepository>();
[UnitOfWork]//这个特性以及方法头里面的virtual很重要
public async virtual Task HandleEventAsync(BookRecordEto eventData)
{
//获取购买记录
var record = await BoughtRecordRepository.GetQueryableAsync();
var recordList = await AsyncExecuter.ToListAsync(record);
if(recordList.Count() != 0){
var boughtRecord = ObjectMapper.Map(eventData, new BoughtRecord());
//插入一条数据
await BoughtRecordRepository.InsertAsync(boughtRecord);
}
}
}
总结
标签:set,string,get,AbpVnext,await,总线,book,public,分布式 来源: https://www.cnblogs.com/Tamper/p/16481846.html