EventConsumer.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. namespace Admin.NET.Core;
  7. /// <summary>
  8. /// Redis 消息扩展
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. public class EventConsumer<T> : IDisposable
  12. {
  13. private Task _consumerTask;
  14. private CancellationTokenSource _consumerCts;
  15. /// <summary>
  16. /// 消费者
  17. /// </summary>
  18. public IProducerConsumer<T> Consumer { get; }
  19. /// <summary>
  20. /// ConsumerBuilder
  21. /// </summary>
  22. public FullRedis Builder { get; set; }
  23. /// <summary>
  24. /// 消息回调
  25. /// </summary>
  26. public event EventHandler<T> Received;
  27. /// <summary>
  28. /// 构造函数
  29. /// </summary>
  30. public EventConsumer(FullRedis redis, string routeKey)
  31. {
  32. Builder = redis;
  33. Consumer = Builder.GetQueue<T>(routeKey);
  34. }
  35. /// <summary>
  36. /// 启动
  37. /// </summary>
  38. /// <exception cref="InvalidOperationException"></exception>
  39. public void Start()
  40. {
  41. if (Consumer is null)
  42. {
  43. throw new InvalidOperationException("Subscribe first using the Consumer.Subscribe() function");
  44. }
  45. if (_consumerTask != null)
  46. {
  47. return;
  48. }
  49. _consumerCts = new CancellationTokenSource();
  50. var ct = _consumerCts.Token;
  51. _consumerTask = Task.Factory.StartNew(() =>
  52. {
  53. while (!ct.IsCancellationRequested)
  54. {
  55. var cr = Consumer.TakeOne(10);
  56. if (cr == null) continue;
  57. Received?.Invoke(this, cr);
  58. }
  59. }, ct, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  60. }
  61. /// <summary>
  62. /// 停止
  63. /// </summary>
  64. /// <returns></returns>
  65. public async Task Stop()
  66. {
  67. if (_consumerCts == null || _consumerTask == null) return;
  68. _consumerCts.Cancel();
  69. try
  70. {
  71. await _consumerTask;
  72. }
  73. finally
  74. {
  75. _consumerTask = null;
  76. _consumerCts = null;
  77. }
  78. }
  79. /// <summary>
  80. /// 释放
  81. /// </summary>
  82. public void Dispose()
  83. {
  84. Dispose(true);
  85. GC.SuppressFinalize(this);
  86. }
  87. /// <summary>
  88. /// 释放
  89. /// </summary>
  90. /// <param name="disposing"></param>
  91. protected virtual void Dispose(bool disposing)
  92. {
  93. if (disposing)
  94. {
  95. if (_consumerTask != null)
  96. {
  97. Stop().Wait();
  98. }
  99. Builder.Dispose();
  100. }
  101. }
  102. }