Cap运用的场景比较广,在这里只说事务一致性的运用,只需三个步骤
1 在nuget中添加3个包
DotNetCore.CAP
DotNetCore.CAP.MySql
DotNetCore.CAP.RabbitMQ
2 在Startup.cs文件中添加
//添加CAPEventBus
services.AddCap(x =>
{
x.UseMySql(_configuration["DefaultConnection"]);
x.UseRabbitMQ(mq =>
{
//mq.HostName = "localhost"; //RabitMq服务器地址,依实际情况修改此地址
mq.HostName = "。。。。。"; //RabitMq服务器地址,依实际情况修改此地址
mq.Port = 5672;
mq.UserName = "。。。"; //RabbitMq账号
mq.Password = "。。。"; //RabbitMq密码
});
x.UseDashboard();
x.FailedRetryCount = 5;
});
3最后使用cap 实现事务一致性
在执行数据操作的时候
private readonly ICapPublisher _capPublisher;
private readonly DbContext _dbContext = null;
#region 构造函数注入
public EventsController(ICapPublisher capPublisher, DbContext dbContext)
{
_capPublisher = capPublisher;
_dbContext = dbContext;
}
using (var trans = _dbContext .Database.BeginTransaction(_capPublisher , autoCommit: false))
{
try
{
// 这里写逻辑代码,对数据的操作
var _test1 = test1.Where(p => p.id == 1).FirstOrDefault();//例子
var _test2 = test2.Where(p => p.id== 2).FirstOrDefault();//例子
_dbContext .test1.Update(_test1);
_dbContext .test2.Update(_test2);
_pingJiaeContext.SaveChanges();
//上面保存成功后提交事务
trans.Commit();
}
catch (Exception ex)
{
//事务回滚
trans.Rollback();
throw;
}
}