EventConsumer.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. namespace Admin.NET.Core;
  2. /// <summary>
  3. /// Redis 消息扩展
  4. /// </summary>
  5. /// <typeparam name="T"></typeparam>
  6. public class EventConsumer<T> : IDisposable
  7. {
  8. private Task _consumerTask;
  9. private CancellationTokenSource _consumerCts;
  10. /// <summary>
  11. /// 消费者
  12. /// </summary>
  13. public IProducerConsumer<T> Consumer { get; }
  14. /// <summary>
  15. /// ConsumerBuilder
  16. /// </summary>
  17. public FullRedis Builder { get; set; }
  18. /// <summary>
  19. /// 消息回调
  20. /// </summary>
  21. public event EventHandler<T> Received;
  22. /// <summary>
  23. /// 构造函数
  24. /// </summary>
  25. public EventConsumer(FullRedis redis, string routeKey)
  26. {
  27. Builder = redis;
  28. Consumer = Builder.GetQueue<T>(routeKey);
  29. }
  30. /// <summary>
  31. /// 启动
  32. /// </summary>
  33. /// <exception cref="InvalidOperationException"></exception>
  34. public void Start()
  35. {
  36. if (Consumer is null)
  37. {
  38. throw new InvalidOperationException("Subscribe first using the Consumer.Subscribe() function");
  39. }
  40. if (_consumerTask != null)
  41. {
  42. return;
  43. }
  44. _consumerCts = new CancellationTokenSource();
  45. var ct = _consumerCts.Token;
  46. _consumerTask = Task.Factory.StartNew(() =>
  47. {
  48. while (!ct.IsCancellationRequested)
  49. {
  50. var cr = Consumer.TakeOne(10);
  51. if (cr == null) continue;
  52. Received?.Invoke(this, cr);
  53. }
  54. }, ct, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  55. }
  56. /// <summary>
  57. /// 停止
  58. /// </summary>
  59. /// <returns></returns>
  60. public async Task Stop()
  61. {
  62. if (_consumerCts == null || _consumerTask == null) return;
  63. _consumerCts.Cancel();
  64. try
  65. {
  66. await _consumerTask;
  67. }
  68. finally
  69. {
  70. _consumerTask = null;
  71. _consumerCts = null;
  72. }
  73. }
  74. /// <summary>
  75. /// 释放
  76. /// </summary>
  77. public void Dispose()
  78. {
  79. Dispose(true);
  80. GC.SuppressFinalize(this);
  81. }
  82. /// <summary>
  83. /// 释放
  84. /// </summary>
  85. /// <param name="disposing"></param>
  86. protected virtual void Dispose(bool disposing)
  87. {
  88. if (disposing)
  89. {
  90. if (_consumerTask != null)
  91. {
  92. Stop().Wait();
  93. }
  94. Builder.Dispose();
  95. }
  96. }
  97. }