RabbitMQEventSourceStore.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using RabbitMQ.Client;
  10. using RabbitMQ.Client.Events;
  11. using System.Threading.Channels;
  12. namespace Admin.Core;
  13. /// <summary>
  14. /// RabbitMQ自定义事件源存储器
  15. /// </summary>
  16. public class RabbitMQEventSourceStore : IEventSourceStorer
  17. {
  18. /// <summary>
  19. /// 内存通道事件源存储器
  20. /// </summary>
  21. private readonly Channel<IEventSource> _channel;
  22. /// <summary>
  23. /// 通道对象
  24. /// </summary>
  25. private readonly IModel _model;
  26. /// <summary>
  27. /// 连接对象
  28. /// </summary>
  29. private readonly IConnection _connection;
  30. /// <summary>
  31. /// 路由键
  32. /// </summary>
  33. private readonly string _routeKey;
  34. /// <summary>
  35. /// 构造函数
  36. /// </summary>
  37. /// <param name="factory">连接工厂</param>
  38. /// <param name="routeKey">路由键</param>
  39. /// <param name="capacity">存储器最多能够处理多少消息,超过该容量进入等待写入</param>
  40. public RabbitMQEventSourceStore(ConnectionFactory factory, string routeKey, int capacity)
  41. {
  42. // 配置通道,设置超出默认容量后进入等待
  43. var boundedChannelOptions = new BoundedChannelOptions(capacity)
  44. {
  45. FullMode = BoundedChannelFullMode.Wait
  46. };
  47. // 创建有限容量通道
  48. _channel = Channel.CreateBounded<IEventSource>(boundedChannelOptions);
  49. // 创建连接
  50. _connection = factory.CreateConnection();
  51. _routeKey = routeKey;
  52. // 创建通道
  53. _model = _connection.CreateModel();
  54. // 声明路由队列
  55. _model.QueueDeclare(routeKey, false, false, false, null);
  56. // 创建消息订阅者
  57. var consumer = new EventingBasicConsumer(_model);
  58. // 订阅消息并写入内存 Channel
  59. consumer.Received += (ch, ea) =>
  60. {
  61. // 读取原始消息
  62. var stringEventSource = Encoding.UTF8.GetString(ea.Body.ToArray());
  63. // 转换为 IEventSource,这里可以选择自己喜欢的序列化工具,如果自定义了 EventSource,注意属性是可读可写
  64. var eventSource = JSON.Deserialize<ChannelEventSource>(stringEventSource);
  65. // 写入内存管道存储器
  66. _channel.Writer.WriteAsync(eventSource);
  67. // 确认该消息已被消费
  68. _model.BasicAck(ea.DeliveryTag, false);
  69. };
  70. // 启动消费者 设置为手动应答消息
  71. _model.BasicConsume(routeKey, false, consumer);
  72. }
  73. /// <summary>
  74. /// 将事件源写入存储器
  75. /// </summary>
  76. /// <param name="eventSource">事件源对象</param>
  77. /// <param name="cancellationToken">取消任务 Token</param>
  78. /// <returns><see cref="ValueTask"/></returns>
  79. public async ValueTask WriteAsync(IEventSource eventSource, CancellationToken cancellationToken)
  80. {
  81. // 空检查
  82. if (eventSource == default)
  83. {
  84. throw new ArgumentNullException(nameof(eventSource));
  85. }
  86. // 这里判断是否是 ChannelEventSource 或者 自定义的 EventSource
  87. if (eventSource is ChannelEventSource source)
  88. {
  89. // 序列化,这里可以选择自己喜欢的序列化工具
  90. var data = Encoding.UTF8.GetBytes(JSON.Serialize(source));
  91. // 发布
  92. _model.BasicPublish("", _routeKey, null, data);
  93. }
  94. else
  95. {
  96. // 这里处理动态订阅问题
  97. await _channel.Writer.WriteAsync(eventSource, cancellationToken);
  98. }
  99. }
  100. /// <summary>
  101. /// 从存储器中读取一条事件源
  102. /// </summary>
  103. /// <param name="cancellationToken">取消任务 Token</param>
  104. /// <returns>事件源对象</returns>
  105. public async ValueTask<IEventSource> ReadAsync(CancellationToken cancellationToken)
  106. {
  107. // 读取一条事件源
  108. var eventSource = await _channel.Reader.ReadAsync(cancellationToken);
  109. return eventSource;
  110. }
  111. /// <summary>
  112. /// 释放非托管资源
  113. /// </summary>
  114. public void Dispose()
  115. {
  116. _model.Dispose();
  117. _connection.Dispose();
  118. }
  119. }