Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

77 wiersze
2.9 KiB

  1. using System;
  2. using DotNetCore.CAP;
  3. using Microsoft.AspNetCore.Mvc;
  4. using MongoDB.Bson;
  5. using MongoDB.Driver;
  6. namespace Sample.RabbitMQ.MongoDB.Controllers
  7. {
  8. [Route("api/[controller]")]
  9. [ApiController]
  10. public class ValuesController : ControllerBase
  11. {
  12. private readonly IMongoClient _client;
  13. private readonly ICapPublisher _capBus;
  14. public ValuesController(IMongoClient client, ICapPublisher capBus)
  15. {
  16. _client = client;
  17. _capBus = capBus;
  18. }
  19. [Route("~/without/transaction")]
  20. public IActionResult WithoutTransaction()
  21. {
  22. _capBus.PublishAsync("sample.rabbitmq.mongodb", DateTime.Now);
  23. return Ok();
  24. }
  25. [Route("~/transaction/not/autocommit")]
  26. public IActionResult PublishNotAutoCommit()
  27. {
  28. //NOTE: before your test, your need to create database and collection at first
  29. //注意:MongoDB 不能在事务中创建数据库和集合,所以你需要单独创建它们,模拟一条记录插入则会自动创建
  30. //var mycollection = _client.GetDatabase("test").GetCollection<BsonDocument>("test.collection");
  31. //mycollection.InsertOne(new BsonDocument { { "test", "test" } });
  32. using (var session = _client.StartTransaction(_capBus, autoCommit: false))
  33. {
  34. var collection = _client.GetDatabase("test").GetCollection<BsonDocument>("test.collection");
  35. collection.InsertOne(session, new BsonDocument { { "hello", "world" } });
  36. _capBus.Publish("sample.rabbitmq.mongodb", DateTime.Now);
  37. session.CommitTransaction();
  38. }
  39. return Ok();
  40. }
  41. [Route("~/transaction/autocommit")]
  42. public IActionResult PublishWithoutTrans()
  43. {
  44. //NOTE: before your test, your need to create database and collection at first
  45. //注意:MongoDB 不能在事务中创建数据库和集合,所以你需要单独创建它们,模拟一条记录插入则会自动创建
  46. //var mycollection = _client.GetDatabase("test").GetCollection<BsonDocument>("test.collection");
  47. //mycollection.InsertOne(new BsonDocument { { "test", "test" } });
  48. using (var session = _client.StartTransaction(_capBus, autoCommit: true))
  49. {
  50. var collection = _client.GetDatabase("test").GetCollection<BsonDocument>("test.collection");
  51. collection.InsertOne(session, new BsonDocument { { "hello", "world" } });
  52. _capBus.Publish("sample.rabbitmq.mongodb", DateTime.Now);
  53. }
  54. return Ok();
  55. }
  56. [NonAction]
  57. [CapSubscribe("sample.rabbitmq.mongodb")]
  58. public void ReceiveMessage(DateTime time)
  59. {
  60. Console.WriteLine($@"{DateTime.Now}, Subscriber invoked, Sent time:{time}");
  61. }
  62. }
  63. }