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