25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

75 satır
2.3 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using DotNetCore.CAP;
  6. using Microsoft.AspNetCore.Mvc;
  7. using MongoDB.Bson;
  8. using MongoDB.Driver;
  9. namespace Sample.RabbitMQ.MongoDB.Controllers
  10. {
  11. [Route("api/[controller]")]
  12. [ApiController]
  13. public class ValuesController : ControllerBase
  14. {
  15. private readonly IMongoClient _client;
  16. private readonly ICapPublisher _capPublisher;
  17. public ValuesController(IMongoClient client, ICapPublisher capPublisher)
  18. {
  19. _client = client;
  20. _capPublisher = capPublisher;
  21. }
  22. [Route("~/publish")]
  23. public IActionResult PublishWithSession()
  24. {
  25. using (var session = _client.StartSession())
  26. {
  27. session.StartTransaction();
  28. var collection = _client.GetDatabase("TEST").GetCollection<BsonDocument>("test");
  29. collection.InsertOne(session, new BsonDocument { { "hello", "world" } });
  30. _capPublisher.PublishWithMongo("sample.rabbitmq.mongodb", DateTime.Now, session);
  31. session.CommitTransaction();
  32. }
  33. return Ok();
  34. }
  35. [Route("~/publish_rollback")]
  36. public IActionResult PublishRollback()
  37. {
  38. using (var session = _client.StartSession())
  39. {
  40. try
  41. {
  42. session.StartTransaction();
  43. _capPublisher.PublishWithMongo("sample.rabbitmq.mongodb", DateTime.Now, session);
  44. throw new Exception("Foo");
  45. }
  46. catch (System.Exception ex)
  47. {
  48. session.AbortTransaction();
  49. return StatusCode(500, ex.Message);
  50. }
  51. }
  52. }
  53. [Route("~/publish_without_session")]
  54. public IActionResult PublishWithoutSession()
  55. {
  56. _capPublisher.PublishWithMongo("sample.rabbitmq.mongodb", DateTime.Now);
  57. return Ok();
  58. }
  59. [NonAction]
  60. [CapSubscribe("sample.rabbitmq.mongodb")]
  61. public void ReceiveMessage(DateTime time)
  62. {
  63. Console.WriteLine("[sample.rabbitmq.mongodb] message received: " + DateTime.Now + ",sent time: " + time);
  64. }
  65. }
  66. }