EventConsumer.cs 2.8 KB

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