Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

78 строки
2.3 KiB

  1. using System;
  2. using System.Data;
  3. using System.Threading.Tasks;
  4. using Dapper;
  5. using DotNetCore.CAP;
  6. using Microsoft.AspNetCore.Mvc;
  7. using MySql.Data.MySqlClient;
  8. namespace Sample.RabbitMQ.MySql.Controllers
  9. {
  10. [Route("api/[controller]")]
  11. public class ValuesController : Controller
  12. {
  13. private readonly ICapPublisher _capBus;
  14. public ValuesController(ICapPublisher capPublisher)
  15. {
  16. _capBus = capPublisher;
  17. }
  18. [Route("~/without/transaction")]
  19. public async Task<IActionResult> WithoutTransaction()
  20. {
  21. await _capBus.PublishAsync("sample.rabbitmq.mysql", DateTime.Now);
  22. return Ok();
  23. }
  24. [Route("~/adonet/transaction")]
  25. public IActionResult AdonetWithTransaction()
  26. {
  27. using (var connection = new MySqlConnection(AppDbContext.ConnectionString))
  28. {
  29. using (var transaction = connection.BeginTransaction(_capBus, autoCommit: false))
  30. {
  31. //your business code
  32. connection.Execute("insert into test(name) values('test')", transaction: (IDbTransaction)transaction.DbTransaction);
  33. for (int i = 0; i < 5; i++)
  34. {
  35. _capBus.Publish("sample.rabbitmq.mysql", DateTime.Now);
  36. }
  37. transaction.Commit();
  38. }
  39. }
  40. return Ok();
  41. }
  42. [Route("~/ef/transaction")]
  43. public IActionResult EntityFrameworkWithTransaction([FromServices]AppDbContext dbContext)
  44. {
  45. using (var trans = dbContext.Database.BeginTransaction(_capBus, autoCommit: false))
  46. {
  47. dbContext.Persons.Add(new Person() { Name = "ef.transaction" });
  48. for (int i = 0; i < 5; i++)
  49. {
  50. _capBus.Publish("sample.rabbitmq.mysql", DateTime.Now);
  51. }
  52. dbContext.SaveChanges();
  53. trans.Commit();
  54. }
  55. return Ok();
  56. }
  57. [NonAction]
  58. [CapSubscribe("#.rabbitmq.mysql")]
  59. public void Subscriber(DateTime time)
  60. {
  61. Console.WriteLine($@"{DateTime.Now}, Subscriber invoked, Sent time:{time}");
  62. }
  63. }
  64. }