/// <summary> 发布 </summary> /// <param name="eventBus"></param> /// <param name="event">事件</param> /// <param name="option"></param> public static Task Publish(this IEventBus eventBus, DEvent @event, PublishOption option = null) { var key = @event.GetType().GetRouteKey(); return(eventBus.Publish(key, @event, option)); }
public abstract Task Publish(string key, byte[] message, PublishOption option = null);
/// <summary> 发布消息 </summary> /// <param name="key"></param> /// <param name="message"></param> /// <param name="option"></param> /// <returns></returns> public override async Task Publish(string key, byte[] message, PublishOption option = null) { if (!_connection.IsConnected) { _connection.TryConnect(); } RabbitMqPublishOption opt; if (option == null) { opt = new RabbitMqPublishOption(); } else if (option is RabbitMqPublishOption rbOpt) { opt = rbOpt; } else { opt = new RabbitMqPublishOption { Delay = option.Delay, Durable = option.Durable, Headers = option.Headers } }; var policy = Policy.Handle <BrokerUnreachableException>() .Or <SocketException>() .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { _logger.LogWarning(ex, ex.ToString()); }); await policy.ExecuteAsync(() => { using (var channel = _connection.CreateModel()) { var prop = channel.CreateBasicProperties(); prop.DeliveryMode = 2; if (opt.Headers != null) { if (prop.Headers == null) { prop.Headers = new Dictionary <string, object>(); } foreach (var header in opt.Headers) { prop.Headers.AddOrUpdate(header.Key, header.Value); } } //声明Exchange var exchange = string.IsNullOrWhiteSpace(opt.Exchange) ? _brokerName : opt.Exchange; channel.ExchangeDeclare(exchange, opt.ExchangeType, opt.Durable); if (opt.Subscribe != null && opt.Subscribe.IsValid) { DeclareAndBindQueue(opt.Subscribe.Queue, opt.Subscribe.RouteKey, opt.Subscribe); } if (opt.Delay.HasValue) { channel.DelayPublish(exchange, key, message, opt.Delay.Value, prop); } else { channel.BasicPublish(exchange, key, prop, message); } } return(Task.CompletedTask); }); }
public Task Publish(string key, object message, PublishOption option = null) { var data = Codec.Encode(message); return(Publish(key, data, option)); }