|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Net.Http; |
| 5 | +using System.Text; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Microsoft.Extensions.Configuration; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | +using MQ.Internal; |
| 11 | +using Newtonsoft.Json; |
| 12 | +using RabbitMQ.Client; |
| 13 | +using RabbitMQ.Client.Events; |
| 14 | +using Microsoft.Extensions.DependencyInjection; |
| 15 | +namespace MQ |
| 16 | +{ |
| 17 | + public class EventBus |
| 18 | + { |
| 19 | + static SpinLock sl = new SpinLock(); |
| 20 | + static JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); |
| 21 | + static EventBusSettings settings; |
| 22 | + static ILogger _logger; |
| 23 | + static CacheManager _CacheManager; |
| 24 | + static EventBus() |
| 25 | + { |
| 26 | + setting.DateFormatString = "yyyy/MM/dd HH:mm:ss.fff"; |
| 27 | + } |
| 28 | + /// <summary> |
| 29 | + /// |
| 30 | + /// </summary> |
| 31 | + /// <typeparam name="T"></typeparam> |
| 32 | + /// <param name="productId"></param> |
| 33 | + /// <param name="topic">exchange</param> |
| 34 | + /// <param name="tag">routingKey</param> |
| 35 | + /// <param name="id"></param> |
| 36 | + /// <param name="message"></param> |
| 37 | + public static ulong Publish<T>(string productId, string topic, string tag, string id, T message) |
| 38 | + { |
| 39 | + var t = typeof(T); |
| 40 | + string msgStr; |
| 41 | + if (t == typeof(string)) |
| 42 | + msgStr = message.ToString(); |
| 43 | + else |
| 44 | + msgStr = Newtonsoft.Json.JsonConvert.SerializeObject(message, t, setting); |
| 45 | + |
| 46 | + var msg = Encoding.UTF8.GetBytes(msgStr); |
| 47 | + bool reflock = false; |
| 48 | + sl.Enter(ref reflock); |
| 49 | + try |
| 50 | + { |
| 51 | + var channel = _CacheManager.GetChannel(productId); |
| 52 | + var pubNo = channel.NextPublishSeqNo; |
| 53 | + channel.BasicPublish(topic, tag, false, null, msg); |
| 54 | + return pubNo; |
| 55 | + } |
| 56 | + catch (Exception ex) |
| 57 | + { |
| 58 | + } |
| 59 | + finally |
| 60 | + { |
| 61 | + if (reflock) |
| 62 | + sl.Exit(); |
| 63 | + } |
| 64 | + return 0; |
| 65 | + } |
| 66 | + /// <summary> |
| 67 | + /// |
| 68 | + /// </summary> |
| 69 | + /// <typeparam name="T"></typeparam> |
| 70 | + /// <param name="productId"></param> |
| 71 | + /// <param name="topic">集群消费:queuename;广播消费:exchange</param> |
| 72 | + /// <param name="action"></param> |
| 73 | + /// <param name="options"></param> |
| 74 | + public static async void Subscribe<T>(string productId, string topic, Func<T, bool> action, SubscribeOptions options = null) |
| 75 | + { |
| 76 | + options = options ?? SubscribeOptions.Default; |
| 77 | + var queueName = topic; |
| 78 | + var channel = _CacheManager.GetChannel(productId); |
| 79 | + |
| 80 | + if (options.Model == MessageModel.Broadcasting) |
| 81 | + { |
| 82 | + var hostName = System.Net.Dns.GetHostName(); |
| 83 | + var ipaddress = await System.Net.Dns.GetHostEntryAsync(hostName).ConfigureAwait(false); |
| 84 | + var ip = ipaddress.AddressList.FirstOrDefault(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString() ?? hostName; |
| 85 | + var fanoutQueueName = ip + "." + productId + "." + topic + "." + DateTime.UtcNow.Ticks; |
| 86 | + channel.QueueDeclare(queue: fanoutQueueName); |
| 87 | + channel.QueueBind(fanoutQueueName, topic, "", null); |
| 88 | + queueName = fanoutQueueName; |
| 89 | + } |
| 90 | + |
| 91 | + var consumer = new EventingBasicConsumer(channel); |
| 92 | + consumer.Shutdown += (obj, ea) => |
| 93 | + { |
| 94 | + _logger.LogError("eventbus.consumer.shutdown:" + ea.ToJson()); |
| 95 | + }; |
| 96 | + channel.BasicQos(0, 1, false); |
| 97 | + var tx = typeof(T) == typeof(string); |
| 98 | + consumer.Received += (obj, ea) => |
| 99 | + { |
| 100 | + try |
| 101 | + { |
| 102 | + var body = Encoding.UTF8.GetString(ea.Body); |
| 103 | + var result = false; |
| 104 | + if (tx) |
| 105 | + result = action((T)((object)body)); |
| 106 | + else |
| 107 | + { |
| 108 | + var msg = JsonConvert.DeserializeObject<T>(body, setting); |
| 109 | + result = action(msg); |
| 110 | + } |
| 111 | + if (result) |
| 112 | + { |
| 113 | + consumer.Model.BasicAck(ea.DeliveryTag, true); |
| 114 | + } |
| 115 | + else |
| 116 | + { |
| 117 | + consumer.Model.BasicReject(ea.DeliveryTag, false); |
| 118 | + } |
| 119 | + } |
| 120 | + catch (Exception ex) |
| 121 | + { |
| 122 | + _logger.LogError(0, ex, "eventbus.subscribe.consumer"); |
| 123 | + } |
| 124 | + }; |
| 125 | + _logger.LogInformation("eventbus.subscribe." + queueName); |
| 126 | + channel.BasicConsume(queueName, false, consumer); |
| 127 | + } |
| 128 | + |
| 129 | + public static void Exit() |
| 130 | + { |
| 131 | + ((IDisposable)_CacheManager).Dispose(); |
| 132 | + } |
| 133 | + |
| 134 | + public static void Configure(IConfigurationRoot config, IServiceProvider internalServiceProvider = null) |
| 135 | + { |
| 136 | + var logger = internalServiceProvider?.GetService<ILogger<EventBus>>(); |
| 137 | + _logger = logger; |
| 138 | + _CacheManager = new CacheManager(); |
| 139 | + _CacheManager.Configure(new EventBusSettings(config, logger)); |
| 140 | + } |
| 141 | + |
| 142 | + } |
| 143 | +} |
0 commit comments