RedisEventSourceStorer.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using NewLife.Caching.Queues;
  7. using Newtonsoft.Json;
  8. using System.Threading.Channels;
  9. namespace Admin.NET.Core;
  10. /// <summary>
  11. /// Redis自定义事件源存储器
  12. /// </summary>
  13. /// <remarks>
  14. /// 在集群部署时,一般每一个消息只由一个服务节点消费一次。
  15. /// 有些特殊情情要通知到服务器群中的每一个节点(比如需要强制加载某些配置、重点服务等),
  16. /// 在这种情况下就要以“broadcast:”开头来定义EventId,
  17. /// 本系统会把“broadcast:”开头的事件视为“广播消息”保证集群中的每一个服务节点都能消费得到这个消息
  18. /// </remarks>
  19. public sealed class RedisEventSourceStorer : IEventSourceStorer, IDisposable
  20. {
  21. /// <summary>
  22. /// 消费者
  23. /// </summary>
  24. private readonly EventConsumer<ChannelEventSource> _eventConsumer;
  25. /// <summary>
  26. /// 内存通道事件源存储器
  27. /// </summary>
  28. private readonly Channel<IEventSource> _channel;
  29. private IProducerConsumer<ChannelEventSource> _queueSingle;
  30. private RedisStream<string> _queueBroadcast;
  31. private ILogger<RedisEventSourceStorer> _logger;
  32. /// <summary>
  33. /// 构造函数
  34. /// </summary>
  35. /// <param name="cacheProvider">Redis 连接对象</param>
  36. /// <param name="routeKey">路由键</param>
  37. /// <param name="capacity">存储器最多能够处理多少消息,超过该容量进入等待写入</param>
  38. public RedisEventSourceStorer(ICacheProvider cacheProvider, string routeKey, int capacity)
  39. {
  40. _logger = App.GetRequiredService<ILogger<RedisEventSourceStorer>>();
  41. // 配置通道,设置超出默认容量后进入等待
  42. var boundedChannelOptions = new BoundedChannelOptions(capacity)
  43. {
  44. FullMode = BoundedChannelFullMode.Wait
  45. };
  46. // 创建有限容量通道
  47. _channel = Channel.CreateBounded<IEventSource>(boundedChannelOptions);
  48. //_redis = redis as FullRedis;
  49. // 创建广播消息订阅者,即所有服务器节点都能收到消息(用来发布重启、Reload配置等消息)
  50. FullRedis redis = (FullRedis)cacheProvider.Cache;
  51. var clusterOpt = App.GetConfig<ClusterOptions>("Cluster", true);
  52. _queueBroadcast = redis.GetStream<string>(routeKey + ":broadcast");
  53. _queueBroadcast.Group = clusterOpt.ServerId;//根据服务器标识分配到不同的分组里
  54. _queueBroadcast.Expire = TimeSpan.FromSeconds(10);//消息10秒过期()
  55. _queueBroadcast.ConsumeAsync(OnConsumeBroadcast);
  56. // 创建队列消息订阅者,只要有一个服务节点消费了消息即可
  57. _queueSingle = redis.GetQueue<ChannelEventSource>(routeKey + ":single");
  58. _eventConsumer = new EventConsumer<ChannelEventSource>(_queueSingle);
  59. // 订阅消息写入 Channel
  60. _eventConsumer.Received += async (send, cr) =>
  61. {
  62. // var oriColor = Console.ForegroundColor;
  63. try
  64. {
  65. ChannelEventSource ces = (ChannelEventSource)cr;
  66. await ConsumeChannelEventSourceAsync(ces, ces.CancellationToken);
  67. }
  68. catch (Exception e)
  69. {
  70. _logger.LogError(e, "处理Received中的消息产生错误!");
  71. }
  72. };
  73. _eventConsumer.Start();
  74. }
  75. private async Task OnConsumeBroadcast(string source, Message message, CancellationToken token)
  76. {
  77. ChannelEventSource ces = JsonConvert.DeserializeObject<ChannelEventSource>(source);
  78. await ConsumeChannelEventSourceAsync(ces, token);
  79. }
  80. private async Task ConsumeChannelEventSourceAsync(ChannelEventSource ces, CancellationToken cancel = default)
  81. {
  82. // 打印测试事件
  83. if (ces.EventId != null && ces.EventId.IndexOf(":Test") > 0)
  84. {
  85. var oriColor = Console.ForegroundColor;
  86. Console.ForegroundColor = ConsoleColor.Green;
  87. Console.WriteLine($"有消息要处理{ces.EventId},{ces.Payload}");
  88. Console.ForegroundColor = oriColor;
  89. }
  90. await _channel.Writer.WriteAsync(ces, cancel);
  91. }
  92. /// <summary>
  93. /// 将事件源写入存储器
  94. /// </summary>
  95. /// <param name="eventSource">事件源对象</param>
  96. /// <param name="cancellationToken">取消任务 Token</param>
  97. /// <returns><see cref="ValueTask"/></returns>
  98. public async ValueTask WriteAsync(IEventSource eventSource, CancellationToken cancellationToken)
  99. {
  100. // 空检查
  101. if (eventSource == default)
  102. throw new ArgumentNullException(nameof(eventSource));
  103. // 这里判断是否是 ChannelEventSource 或者 自定义的 EventSource
  104. if (eventSource is ChannelEventSource source)
  105. {
  106. // 异步发布
  107. await Task.Factory.StartNew(() =>
  108. {
  109. if (source.EventId != null && source.EventId.StartsWith("broadcast:"))
  110. {
  111. string str = JsonConvert.SerializeObject(source);
  112. _queueBroadcast.Add(str);
  113. }
  114. else
  115. {
  116. _queueSingle.Add(source);
  117. }
  118. }, cancellationToken, TaskCreationOptions.LongRunning, System.Threading.Tasks.TaskScheduler.Default);
  119. }
  120. else
  121. {
  122. // 处理动态订阅问题
  123. await _channel.Writer.WriteAsync(eventSource, cancellationToken);
  124. }
  125. }
  126. /// <summary>
  127. /// 从存储器中读取一条事件源
  128. /// </summary>
  129. /// <param name="cancellationToken">取消任务 Token</param>
  130. /// <returns>事件源对象</returns>
  131. public async ValueTask<IEventSource> ReadAsync(CancellationToken cancellationToken)
  132. {
  133. // 读取一条事件源
  134. var eventSource = await _channel.Reader.ReadAsync(cancellationToken);
  135. return eventSource;
  136. }
  137. /// <summary>
  138. /// 释放非托管资源
  139. /// </summary>
  140. public async void Dispose()
  141. {
  142. await _eventConsumer.Stop();
  143. GC.SuppressFinalize(this);
  144. }
  145. }