RedisEventSourceStorer.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. ConsumeChannelEventSourceAsync(ces,ces.CancellationToken).GetAwaiter().GetResult();
  68. };
  69. _eventConsumer.Start();
  70. }
  71. private async Task OnConsumeBroadcast(string source, Message message, CancellationToken token)
  72. {
  73. ChannelEventSource ces = JsonConvert.DeserializeObject<ChannelEventSource>(source);
  74. await ConsumeChannelEventSourceAsync(ces,token);
  75. }
  76. private async Task ConsumeChannelEventSourceAsync(ChannelEventSource ces,CancellationToken cancel = default)
  77. {
  78. // 打印测试事件
  79. if (ces.EventId != null && ces.EventId.IndexOf(":Test") > 0)
  80. {
  81. var oriColor = Console.ForegroundColor;
  82. Console.ForegroundColor = ConsoleColor.Green;
  83. Console.WriteLine($"有消息要处理{ces.EventId},{ces.Payload}");
  84. Console.ForegroundColor = oriColor;
  85. }
  86. await _channel.Writer.WriteAsync(ces,cancel);
  87. }
  88. /// <summary>
  89. /// 将事件源写入存储器
  90. /// </summary>
  91. /// <param name="eventSource">事件源对象</param>
  92. /// <param name="cancellationToken">取消任务 Token</param>
  93. /// <returns><see cref="ValueTask"/></returns>
  94. public async ValueTask WriteAsync(IEventSource eventSource, CancellationToken cancellationToken)
  95. {
  96. // 空检查
  97. if (eventSource == default)
  98. throw new ArgumentNullException(nameof(eventSource));
  99. // 这里判断是否是 ChannelEventSource 或者 自定义的 EventSource
  100. if (eventSource is ChannelEventSource source)
  101. {
  102. // 异步发布
  103. await Task.Factory.StartNew(() =>
  104. {
  105. if (source.EventId != null && source.EventId.StartsWith("broadcast:"))
  106. {
  107. string str = JsonConvert.SerializeObject(source);
  108. _queueBroadcast.Add(str);
  109. }
  110. else
  111. {
  112. _queueSingle.Add(source);
  113. }
  114. }, cancellationToken, TaskCreationOptions.LongRunning, System.Threading.Tasks.TaskScheduler.Default);
  115. }
  116. else
  117. {
  118. // 处理动态订阅问题
  119. await _channel.Writer.WriteAsync(eventSource, cancellationToken);
  120. }
  121. }
  122. /// <summary>
  123. /// 从存储器中读取一条事件源
  124. /// </summary>
  125. /// <param name="cancellationToken">取消任务 Token</param>
  126. /// <returns>事件源对象</returns>
  127. public async ValueTask<IEventSource> ReadAsync(CancellationToken cancellationToken)
  128. {
  129. // 读取一条事件源
  130. var eventSource = await _channel.Reader.ReadAsync(cancellationToken);
  131. return eventSource;
  132. }
  133. /// <summary>
  134. /// 释放非托管资源
  135. /// </summary>
  136. public async void Dispose()
  137. {
  138. await _eventConsumer.Stop();
  139. GC.SuppressFinalize(this);
  140. }
  141. }