RedisEventSourceStorer.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. private ILogger<RedisEventSourceStorer> _logger;
  22. /// <summary>
  23. /// 消费者
  24. /// </summary>
  25. private readonly EventConsumer<ChannelEventSource> _eventConsumer;
  26. /// <summary>
  27. /// 内存通道事件源存储器
  28. /// </summary>
  29. private readonly Channel<IEventSource> _channel;
  30. private IProducerConsumer<ChannelEventSource> _queueSingle;
  31. private RedisStream<string> _queueBroadcast;
  32. /// <summary>
  33. /// 路由键
  34. /// </summary>
  35. private readonly string _routeKey;
  36. /// <summary>
  37. /// 构造函数
  38. /// </summary>
  39. /// <param name="cacheProvider">Redis 连接对象</param>
  40. /// <param name="routeKey">路由键</param>
  41. /// <param name="capacity">存储器最多能够处理多少消息,超过该容量进入等待写入</param>
  42. public RedisEventSourceStorer(ICacheProvider cacheProvider, string routeKey, int capacity)
  43. {
  44. _logger = App.GetRequiredService<ILogger<RedisEventSourceStorer>>();
  45. // 配置通道,设置超出默认容量后进入等待
  46. var boundedChannelOptions = new BoundedChannelOptions(capacity)
  47. {
  48. FullMode = BoundedChannelFullMode.Wait
  49. };
  50. // 创建有限容量通道
  51. _channel = Channel.CreateBounded<IEventSource>(boundedChannelOptions);
  52. //_redis = redis as FullRedis;
  53. _routeKey = routeKey;
  54. // 创建广播消息订阅者,即所有服务器节点都能收到消息(用来发布重启、Reload配置等消息)
  55. FullRedis redis = (FullRedis)cacheProvider.Cache;
  56. var clusterOpt = App.GetConfig<ClusterOptions>("Cluster", true);
  57. _queueBroadcast = redis.GetStream<string>(routeKey + ":broadcast");
  58. _queueBroadcast.Group = clusterOpt.ServerId;//根据服务器标识分配到不同的分组里
  59. _queueBroadcast.Expire = TimeSpan.FromSeconds(10);//消息10秒过期()
  60. _queueBroadcast.ConsumeAsync(OnConsumeBroadcast);
  61. // 创建队列消息订阅者,只要有一个服务节点消费了消息即可
  62. _queueSingle = redis.GetQueue<ChannelEventSource>(routeKey + ":single");
  63. _eventConsumer = new EventConsumer<ChannelEventSource>(_queueSingle);
  64. // 订阅消息写入 Channel
  65. _eventConsumer.Received += async (send, cr) =>
  66. {
  67. // var oriColor = Console.ForegroundColor;
  68. try
  69. {
  70. ChannelEventSource ces = (ChannelEventSource)cr;
  71. await ConsumeChannelEventSourceAsync(ces, ces.CancellationToken);
  72. }
  73. catch (Exception e)
  74. {
  75. _logger.LogError(e,"处理Received中的消息产生错误!");
  76. }
  77. };
  78. _eventConsumer.Start();
  79. }
  80. private async Task OnConsumeBroadcast(string source, Message message, CancellationToken token)
  81. {
  82. ChannelEventSource ces = JsonConvert.DeserializeObject<ChannelEventSource>(source);
  83. await ConsumeChannelEventSourceAsync(ces,token);
  84. }
  85. private async Task ConsumeChannelEventSourceAsync(ChannelEventSource ces,CancellationToken cancel = default)
  86. {
  87. // 打印测试事件
  88. if (ces.EventId != null && ces.EventId.IndexOf(":Test") > 0)
  89. {
  90. var oriColor = Console.ForegroundColor;
  91. Console.ForegroundColor = ConsoleColor.Green;
  92. Console.WriteLine($"有消息要处理{ces.EventId},{ces.Payload}");
  93. Console.ForegroundColor = oriColor;
  94. }
  95. await _channel.Writer.WriteAsync(ces,cancel);
  96. }
  97. /// <summary>
  98. /// 将事件源写入存储器
  99. /// </summary>
  100. /// <param name="eventSource">事件源对象</param>
  101. /// <param name="cancellationToken">取消任务 Token</param>
  102. /// <returns><see cref="ValueTask"/></returns>
  103. public async ValueTask WriteAsync(IEventSource eventSource, CancellationToken cancellationToken)
  104. {
  105. // 空检查
  106. if (eventSource == default)
  107. throw new ArgumentNullException(nameof(eventSource));
  108. // 这里判断是否是 ChannelEventSource 或者 自定义的 EventSource
  109. if (eventSource is ChannelEventSource source)
  110. {
  111. // 异步发布
  112. await Task.Factory.StartNew(() =>
  113. {
  114. if (source.EventId != null && source.EventId.StartsWith("broadcast:"))
  115. {
  116. string str = JsonConvert.SerializeObject(source);
  117. _queueBroadcast.Add(str);
  118. }
  119. else
  120. {
  121. _queueSingle.Add(source);
  122. }
  123. }, cancellationToken, TaskCreationOptions.LongRunning, System.Threading.Tasks.TaskScheduler.Default);
  124. }
  125. else
  126. {
  127. // 处理动态订阅问题
  128. await _channel.Writer.WriteAsync(eventSource, cancellationToken);
  129. }
  130. }
  131. /// <summary>
  132. /// 从存储器中读取一条事件源
  133. /// </summary>
  134. /// <param name="cancellationToken">取消任务 Token</param>
  135. /// <returns>事件源对象</returns>
  136. public async ValueTask<IEventSource> ReadAsync(CancellationToken cancellationToken)
  137. {
  138. // 读取一条事件源
  139. var eventSource = await _channel.Reader.ReadAsync(cancellationToken);
  140. return eventSource;
  141. }
  142. /// <summary>
  143. /// 释放非托管资源
  144. /// </summary>
  145. public async void Dispose()
  146. {
  147. await _eventConsumer.Stop();
  148. GC.SuppressFinalize(this);
  149. }
  150. }