Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

ValuesController.cs 2.5 KiB

5 anni fa
5 anni fa
5 anni fa
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 MySqlConnector;
  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, true))
  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. }
  38. }
  39. return Ok();
  40. }
  41. [Route("~/ef/transaction")]
  42. public IActionResult EntityFrameworkWithTransaction([FromServices]AppDbContext dbContext)
  43. {
  44. using (var trans = dbContext.Database.BeginTransaction(_capBus, autoCommit: false))
  45. {
  46. dbContext.Persons.Add(new Person() { Name = "ef.transaction" });
  47. for (int i = 0; i < 1; i++)
  48. {
  49. _capBus.Publish("sample.rabbitmq.mysql", DateTime.Now);
  50. }
  51. dbContext.SaveChanges();
  52. trans.Commit();
  53. }
  54. return Ok();
  55. }
  56. [NonAction]
  57. [CapSubscribe("sample.rabbitmq.mysql")]
  58. public void Subscriber(DateTime p)
  59. {
  60. Console.WriteLine($@"{DateTime.Now} Subscriber invoked, Info: {p}");
  61. }
  62. [NonAction]
  63. [CapSubscribe("sample.rabbitmq.mysql", Group = "group.test2")]
  64. public void Subscriber2(DateTime p, [FromCap]CapHeader header)
  65. {
  66. Console.WriteLine($@"{DateTime.Now} Subscriber invoked, Info: {p}");
  67. }
  68. }
  69. }