在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本篇文章旨在描述如何在 在本示例中 ,我们主要是基于 一、发布端事务由于大部分人都是在 1、创建一个 public class CapTransactionFilterAttribute : TypeFilterAttribute { public CapTransactionFilterAttribute() : base(typeof(TransactionActionFilter)) { } public class TransactionActionFilter : IActionFilter { private IDbContextTransaction _transaction; public void OnActionExecuting(ActionExecutingContext context) { var dbContext = context.HttpContext.RequestServices.GetRequiredService<AppDbContext>(); var capPublisher = context.HttpContext.RequestServices.GetService<ICapPublisher>(); _transaction = dbContext.Database.BeginTransaction(capPublisher); } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception == null) { _transaction.Commit(); } else { _transaction.Rollback(); } _transaction?.Dispose(); } } } 2、使用方式,在需要进行事务控制的 [Route("~/ef/trans-filter")] [TypeFilter(typeof(CapTransactionFilterAttribute))] public IActionResult EntityFrameworkWithTransactionFilter( [FromServices] AppDbContext dbContext) { dbContext.Persons.Add(new Person() { Name = "ef.transaction" }); _capBus.Publish("sample.rabbitmq.mysql", DateTime.Now); dbContext.SaveChanges(); return Ok(); } 二、消费端事务消费端自动事务主要利用 1、创建一个 CAP 过滤器public class MyCapFilter : SubscribeFilter { private readonly AppDbContext _dbContext; private IDbContextTransaction _transaction; public MyCapFilter(AppDbContext dbContext) { _dbContext = dbContext; } public override void OnSubscribeExecuting(ExecutingContext context) { _transaction = _dbContext.Database.BeginTransaction(); } public override void OnSubscribeExecuted(ExecutedContext context) { _transaction.Commit(); } public override void OnSubscribeException(DotNetCore.CAP.Filter.ExceptionContext context) { _transaction.Rollback(); } } 2、配置过滤器services.AddCap(opt => { // *** }.AddSubscribeFilter<MyCapFilter>(); 以上就是消费端的一个简单示例。 到此这篇关于在 |
请发表评论