public Task FuturePublishAsync <T>(DateTime futurePublishDate, string cancellationKey, T message) where T : class { Preconditions.CheckNotNull(message, "message"); var messageType = typeof(ScheduleMe); return(publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).Then(exchange => { var typeName = typeNameSerializer.Serialize(typeof(T)); var messageBody = serializer.MessageToBytes(message); var scheduleMe = new ScheduleMe { WakeTime = futurePublishDate, BindingKey = typeName, CancellationKey = cancellationKey, InnerMessage = messageBody }; var easyNetQMessage = new Message <ScheduleMe>(scheduleMe) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType) } }; return advancedBus.PublishAsync(exchange, conventions.TopicNamingConvention(messageType), false, false, easyNetQMessage); })); }
public async Task <Message> SendAsync(string route, Message message, CancellationToken cancellationToken = default) { var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); cts.CancelAfter(DefaultTimeout); var correlationId = Guid.NewGuid(); var tcs = new TaskCompletionSource <Message>(TaskCreationOptions.RunContinuationsAsynchronously); RegisterReplyHandler(correlationId, tcs); using (cts.Token.Register(() => RemoveReplyHandler(correlationId))) using (cts.Token.Register(() => tcs.SetCanceled())) { var exchange = await DeclareRpcExchangeAsync(cts.Token); var replyAddress = await SubscribeToReplyAsync(cts.Token); var properties = new MessageProperties { CorrelationId = correlationId.ToString(), ReplyTo = replyAddress, Headers = message.Headers.ToDictionary(x => x.Key, x => (object)x.Value) }; await _bus.PublishAsync(exchange, route, true, properties, message.Body); return(await tcs.Task); } }
public async Task FuturePublishAsync <T>(DateTime futurePublishDate, T message, string cancellationKey = null) where T : class { Preconditions.CheckNotNull(message, "message"); var scheduleMeType = typeof(ScheduleMe); var scheduleMeExchange = await publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, scheduleMeType, ExchangeType.Topic).ConfigureAwait(false); var baseMessageType = typeof(T); var concreteMessageType = message.GetType(); var serializedMessage = messageSerializationStrategy.SerializeMessage(new Message <T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(concreteMessageType) } }); var scheduleMe = new ScheduleMe { WakeTime = futurePublishDate, CancellationKey = cancellationKey, InnerMessage = serializedMessage.Body, MessageProperties = serializedMessage.Properties, BindingKey = typeNameSerializer.Serialize(typeof(T)), ExchangeType = ExchangeType.Topic, Exchange = conventions.ExchangeNamingConvention(baseMessageType), RoutingKey = "#" }; var easyNetQMessage = new Message <ScheduleMe>(scheduleMe) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(scheduleMeType) } }; await advancedBus.PublishAsync(scheduleMeExchange, conventions.TopicNamingConvention(scheduleMeType), false, easyNetQMessage).ConfigureAwait(false); }
public async Task Publish <T>(string exchange, string routingKey, Envelope <T> message) { await _messageBus.PublishAsync(new Exchange(exchange), routingKey, true, new Message <Envelope <T> >(message, new EasyNetQ.MessageProperties { ContentType = "application/json", CorrelationId = message.CorrelationId, MessageId = message.MessageId, })); }
public async Task PublishJobMessage(JobMessage message) { var queueExhange = nameof(JobMessage); var queue2 = _bus.QueueDeclare(queueExhange); var exchange = _bus.ExchangeDeclare(queueExhange, ExchangeType.Topic); _bus.Bind(exchange, queue2, "A.*"); var topic = $"ProjectId.CabinId"; var yourMessage = new Message <string>(JsonConvert.SerializeObject(message)); await _bus.PublishAsync(exchange, "A.*", true, yourMessage); }
/// <inheritdoc /> public virtual async Task PublishAsync <T>(T message, Action <IPublishConfiguration> configure, CancellationToken cancellationToken) { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(configure, "configure"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); var publishConfiguration = new PublishConfiguration(conventions.TopicNamingConvention(typeof(T))); configure(publishConfiguration); var messageType = typeof(T); var advancedMessageProperties = new MessageProperties(); if (publishConfiguration.Priority != null) { advancedMessageProperties.Priority = publishConfiguration.Priority.Value; } if (publishConfiguration.Expires != null) { advancedMessageProperties.Expiration = publishConfiguration.Expires.ToString(); } advancedMessageProperties.DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType); var advancedMessage = new Message <T>(message, advancedMessageProperties); var exchange = await exchangeDeclareStrategy.DeclareExchangeAsync( messageType, ExchangeType.Topic, cts.Token ).ConfigureAwait(false); await advancedBus.PublishAsync( exchange, publishConfiguration.Topic, false, advancedMessage, cts.Token ).ConfigureAwait(false); }
private async Task FuturePublishInternalAsync <T>(TimeSpan messageDelay, T message, string cancellationKey) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckLess(messageDelay, MaxMessageDelay, "messageDelay"); Preconditions.CheckNull(cancellationKey, "cancellationKey"); var delay = Round(messageDelay); var delayString = delay.ToString(@"dd\_hh\_mm\_ss"); var exchangeName = conventions.ExchangeNamingConvention(typeof(T)); var futureExchangeName = exchangeName + "_" + delayString; var futureQueueName = conventions.QueueNamingConvention(typeof(T), delayString); var futureExchange = await advancedBus.ExchangeDeclareAsync(futureExchangeName, ExchangeType.Topic).ConfigureAwait(false); var futureQueue = await advancedBus.QueueDeclareAsync(futureQueueName, perQueueMessageTtl : (int)delay.TotalMilliseconds, deadLetterExchange : exchangeName).ConfigureAwait(false); await advancedBus.BindAsync(futureExchange, futureQueue, "#").ConfigureAwait(false); var easyNetQMessage = new Message <T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(typeof(T)) } }; await advancedBus.PublishAsync(futureExchange, "#", false, false, easyNetQMessage).ConfigureAwait(false); }
public virtual async Task PublishAsync <T>(T message, Action <IPublishConfiguration> configure) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(configure, "configure"); var configuration = new PublishConfiguration(conventions.TopicNamingConvention(typeof(T))); configure(configuration); var messageType = typeof(T); var easyNetQMessage = new Message <T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType) } }; if (configuration.Priority != null) { easyNetQMessage.Properties.Priority = configuration.Priority.Value; } if (configuration.Expires != null) { easyNetQMessage.Properties.Expiration = configuration.Expires.ToString(); } var exchange = await publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).ConfigureAwait(false); await advancedBus.PublishAsync(exchange, configuration.Topic, false, easyNetQMessage).ConfigureAwait(false); }
private async Task FuturePublishInternalAsync <T>(TimeSpan messageDelay, T message, string cancellationKey = null) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckLess(messageDelay, MaxMessageDelay, "messageDelay"); Preconditions.CheckNull(cancellationKey, "cancellationKey"); var exchangeName = conventions.ExchangeNamingConvention(typeof(T)); var futureExchangeName = exchangeName + "_delayed"; var queueName = conventions.QueueNamingConvention(typeof(T), null); var futureExchange = await advancedBus.ExchangeDeclareAsync(futureExchangeName, ExchangeType.Direct, delayed : true).ConfigureAwait(false); var exchange = await advancedBus.ExchangeDeclareAsync(exchangeName, ExchangeType.Topic).ConfigureAwait(false); await advancedBus.BindAsync(futureExchange, exchange, "#").ConfigureAwait(false); var queue = await advancedBus.QueueDeclareAsync(queueName).ConfigureAwait(false); await advancedBus.BindAsync(exchange, queue, "#").ConfigureAwait(false); var easyNetQMessage = new Message <T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(typeof(T)), Headers = new Dictionary <string, object>{ { "x-delay", (int)messageDelay.TotalMilliseconds } } } }; await advancedBus.PublishAsync(futureExchange, "#", false, false, easyNetQMessage).ConfigureAwait(false); }
/// <inheritdoc /> public async Task FuturePublishAsync <T>( T message, TimeSpan delay, Action <IFuturePublishConfiguration> configure, CancellationToken cancellationToken = default ) { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(configure, "configure"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); var publishConfiguration = new FuturePublishConfiguration(conventions.TopicNamingConvention(typeof(T))); configure(publishConfiguration); var topic = publishConfiguration.Topic; var exchange = await exchangeDeclareStrategy.DeclareExchangeAsync( conventions.ExchangeNamingConvention(typeof(T)), ExchangeType.Topic, cts.Token ).ConfigureAwait(false); var delayString = delay.ToString(@"dd\_hh\_mm\_ss"); var futureExchange = await exchangeDeclareStrategy.DeclareExchangeAsync( $"{conventions.ExchangeNamingConvention(typeof(T))}_{delayString}", ExchangeType.Topic, cts.Token ).ConfigureAwait(false); var futureQueue = await advancedBus.QueueDeclareAsync( conventions.QueueNamingConvention(typeof(T), delayString), c => { c.WithMessageTtl(delay); c.WithDeadLetterExchange(exchange); if (setDeadLetterRoutingKey) { c.WithDeadLetterRoutingKey(topic); } }, cts.Token ).ConfigureAwait(false); await advancedBus.BindAsync(futureExchange, futureQueue, topic, cts.Token).ConfigureAwait(false); var properties = new MessageProperties(); if (publishConfiguration.Priority != null) { properties.Priority = publishConfiguration.Priority.Value; } properties.DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(typeof(T)); var advancedMessage = new Message <T>(message, properties); await advancedBus.PublishAsync( futureExchange, topic, configuration.MandatoryPublish, advancedMessage, cts.Token ).ConfigureAwait(false); }
protected Func <IMessage <T>, MessageReceivedInfo, Task> ConsumerHandler <T>(Func <IMessage <T>, ExtendedMessageReceivedInfo, Task> inner) { return(async(message, info) => { var(handled, redeliveryCount) = await HandleRedelivery(message.Properties, info, queue => _easyNetQBus.PublishAsync(Exchange.GetDefault(), queue.Name, true, message) ); if (handled) { return; } _log.LogInformation("Received message. Message queue {queue}, type {type}", info.Queue, typeof(T).Name); await inner.Invoke(message, new ExtendedMessageReceivedInfo(info, redeliveryCount)); }); }
public async Task Handle(CustomerWasCreated notification, CancellationToken cancellationToken) { var message = new Message <ICustomerWasCreated>(notification); var exchange = _bus.ExchangeDeclare("customer-was-created", ExchangeType.Fanout); var queue = _bus.QueueDeclare("customer-was-created"); _bus.Bind(exchange, queue, ""); await _bus.PublishAsync <ICustomerWasCreated>(exchange, "", true, message); }
public async Task PublishAsync <T>(T message, string topic) where T : class { GuardHelper.ArgumentNotNull(() => message); GuardHelper.ArgumentNotEmpty(() => topic); var messageType = typeof(T); var rabbitMessage = GetRabbitMessage(message, messageType); var exchange = await publishExchangeDeclareStrategy.DeclareExchangeAsync( advancedBus, messageType, ExchangeType.Topic).ConfigureAwait(false); await advancedBus.PublishAsync(exchange, topic, rabbitMessage).ConfigureAwait(false); }
public Task PublishAsync <T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); var exchange = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, typeof(T), ExchangeType.Topic); var easyNetQMessage = new Message <T>(message); easyNetQMessage.Properties.DeliveryMode = (byte)(connectionConfiguration.PersistentMessages ? 2 : 1); return(advancedBus.PublishAsync(exchange, topic, false, false, easyNetQMessage)); }
public async Task SendAsync(string route, Message message, CancellationToken cancellationToken = default) { var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var exchange = await DeclareBusExchangeAsync(cts.Token); var properties = new MessageProperties { Headers = message.Headers.ToDictionary(x => x.Key, x => (object)x.Value) }; await _bus.PublishAsync(exchange, route, true, properties, message.Body); }
public Task PublishAsync <T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); var exchangeName = conventions.ExchangeNamingConvention(typeof(T)); var exchange = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, exchangeName); var easyNetQMessage = new Message <T>(message); // by default publish persistent messages easyNetQMessage.Properties.DeliveryMode = 2; return(advancedBus.PublishAsync(exchange, topic, false, false, easyNetQMessage)); }
/// <summary> /// Publish a message as a .NET type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bus">The bus instance</param> /// <param name="exchange">The exchange to publish to</param> /// <param name="routingKey"> /// The routing key for the message. The routing key is used for routing messages depending on the /// exchange configuration. /// </param> /// <param name="mandatory"> /// This flag tells the server how to react if the message cannot be routed to a queue. /// If this flag is true, the server will return an unroutable message with a Return method. /// If this flag is false, the server silently drops the message. /// </param> /// <param name="message">The message to publish</param> /// <param name="cancellationToken">The cancellation token</param> public static void Publish <T>( this IAdvancedBus bus, IExchange exchange, string routingKey, bool mandatory, IMessage <T> message, CancellationToken cancellationToken = default ) { Preconditions.CheckNotNull(bus, "bus"); bus.PublishAsync(exchange, routingKey, mandatory, message, cancellationToken) .GetAwaiter() .GetResult(); }
public virtual Task PublishAsync <T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); var messageType = typeof(T); return(publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).Then(exchange => { var easyNetQMessage = new Message <T>(message) { Properties = { DeliveryMode = (byte)(messageDeliveryModeStrategy.IsPersistent(messageType) ? 2 : 1) } }; return advancedBus.PublishAsync(exchange, topic, false, false, easyNetQMessage); })); }
public async Task PublishAsync <T>(Message <T> message) { _logger.LogDebug("PublishAsync() started."); if (message != null) { var exchange = await BindExchangeWithMessageQueueAsync(_exchangeName); await _advancedBus.PublishAsync(exchange, string.Empty, true, message); } else { _logger.LogError("Unsupported message received. Message ignored."); } _logger.LogDebug("PublishAsync() completed."); }
/// <summary> /// Enqueue message to the Email Worker API for sending a mail /// to the user with his/hers results from the test. /// </summary> /// <param name="notification"></param> /// <param name="cancellationToken"></param> public async Task Handle(UserSubmittedPersonalData notification, CancellationToken cancellationToken) { var results = await _userTestResultRepository.GetByUserAsync(notification.UserIdentifier); var resultsAnalyzer = new UserResultStatAnalyzer(results.ResultStatistics); var mailBody = await CreateMailBodyByTopResultsAsync(resultsAnalyzer.GetTopResults()); var emailModel = new SendUserResultsEmail(notification.Email, mailBody); await _advancedBus.PublishAsync( exchange : _exchange, routingKey : _config.RoutingKey, mandatory : false, message : new Message <SendUserResultsEmail>(emailModel)); }
public virtual async Task PublishAsync <T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); var messageType = typeof(T); var easyNetQMessage = new Message <T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType) } }; var exchange = await publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).ConfigureAwait(false); await advancedBus.PublishAsync(exchange, topic, false, easyNetQMessage).ConfigureAwait(false); }
public async Task <TaskArguments> Handle(RequestCalculationRequest message) { var newTask = new TaskEntity() { A = message.Arguments.A, B = message.Arguments.B, }; var createdTask = _repository.Create(newTask); message.Arguments.Id = createdTask.Id; var exchanger = _advancedBus.ExchangeDeclare(ExchangerNames.Tasks, ExchangeType.Topic); await _advancedBus.PublishAsync(exchanger, MessageTopics.Sum, false, new Message <TaskArguments>(message.Arguments)); return(message.Arguments); }
public async Task Publish(string mes) { var queueExhange = nameof(PublishMessage); var queue2 = _bus.QueueDeclare(queueExhange); var exchange = _bus.ExchangeDeclare(queueExhange, ExchangeType.Topic); _bus.Bind(exchange, queue2, "A.*"); var newMessage = new PublishMessage() { Text = "Hello" }; var topic = $"ProjectId.CabinId"; var yourMessage = new Message <string>(JsonConvert.SerializeObject(new PublishMessage { Text = mes })); await _bus.PublishAsync(exchange, "A.*", true, yourMessage); }
/// <inheritdoc /> public async Task FuturePublishAsync <T>( T message, TimeSpan delay, Action <IFuturePublishConfiguration> configure, CancellationToken cancellationToken = default ) { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(configure, "configure"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); var publishConfiguration = new FuturePublishConfiguration(conventions.TopicNamingConvention(typeof(T))); configure(publishConfiguration); var topic = publishConfiguration.Topic; var exchangeName = conventions.ExchangeNamingConvention(typeof(T)); var futureExchangeName = exchangeName + "_delayed"; var futureExchange = await advancedBus.ExchangeDeclareAsync( futureExchangeName, c => c.AsDelayedExchange(ExchangeType.Topic), cts.Token ).ConfigureAwait(false); var exchange = await advancedBus.ExchangeDeclareAsync( exchangeName, c => c.WithType(ExchangeType.Topic), cts.Token ).ConfigureAwait(false); await advancedBus.BindAsync(futureExchange, exchange, topic, cts.Token).ConfigureAwait(false); var properties = new MessageProperties(); if (publishConfiguration.Priority != null) { properties.Priority = publishConfiguration.Priority.Value; } properties.DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(typeof(T)); await advancedBus.PublishAsync( futureExchange, topic, false, new Message <T>(message, properties).WithDelay(delay), cts.Token ).ConfigureAwait(false); }
public async Task PublishAsync(MessageModel messageAvailable, CancellationToken cancellationToken) { _logger.LogInformation($"Entering {nameof(PublishAsync)}"); try { var exchange = await _advancedBus.ExchangeDeclareAsync(name : _exchanges.ExchangeKey, type : ExchangeType.Direct, cancellationToken : cancellationToken).ConfigureAwait(false); var body = new Message <MessageModel>(messageAvailable); await _advancedBus.PublishAsync(exchange : exchange, routingKey : _routings.RoutingKey, mandatory : false, message : body, cancellationToken : cancellationToken).ConfigureAwait(false); _logger.LogInformation($"Message: {messageAvailable.Text}"); } catch (Exception ex) { _logger.LogError(ex, ex.Message); throw; } }
public async Task SendAsync <T>(T message, TimeSpan?redeliveryDelay = null, int?redeliveryLimit = null, bool persistent = true) { await InitAsync(); var wrapper = new Message <T>(message); if (redeliveryDelay.HasValue) { wrapper.Properties.Headers[MessageHeaders.RedeliveryDelay] = (int)redeliveryDelay.Value.TotalMilliseconds; } if (redeliveryLimit.HasValue) { wrapper.Properties.Headers[MessageHeaders.RedeliveryLimit] = redeliveryLimit.Value; } if (persistent) { wrapper.Properties.DeliveryMode = 2; } await _easyNetQBus.PublishAsync(Exchange.GetDefault(), _messageBus.Value.Queue, true, wrapper); }
public static async Task ResendErrorsAsync(this IAdvancedBus source, string errorQueueName) { var errorQueue = await source.QueueDeclareAsync(errorQueueName); var message = await source.GetMessageAsync(errorQueue); while (message != null) { var utf8Body = Encoding.UTF8.GetString(message.Body); var error = JsonConvert.DeserializeObject <Error>(utf8Body); var errorBodyBytes = Encoding.UTF8.GetBytes(error.Message); var exchange = await source.ExchangeDeclareAsync(error.Exchange, x => { // This can be adjusted to fit the exchange actual configuration x.AsDurable(true); x.AsAutoDelete(false); x.WithType("topic"); }); await source.PublishAsync(exchange, error.RoutingKey, true, error.BasicProperties, errorBodyBytes); message = await source.GetMessageAsync(errorQueue); } }
public async Task SendTopicAsync <T>(T message, string routeKey = "", bool isMandatory = false) where T : class { var exchange = new ExchangeConfig(); if (!_bus.IsConnected) { string errorMessage = ""; _logger.LogError(errorMessage); throw new Exception(""); } _advancedBus.ExchangeDeclare(exchange.Name, exchange.Type); var policy = Policy.Handle <Exception>().WaitAndRetryAsync(_retryAttempts, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, _retryAttempts)), (ex, time) => { string errorMessage = ""; _logger.LogError(errorMessage); throw new Exception(""); }); await policy.ExecuteAsync(async() => await _advancedBus.PublishAsync(exchange, routeKey, isMandatory, new Message <T>(message)).ConfigureAwait(false) ).ConfigureAwait(false); }
public async Task PublishEventAsync(byte[] body, MessageProperties messageProperties, string routing) { await _bus.PublishAsync(await _exchange, routing, false, messageProperties, body); }
/// <inheritdoc/> public async Task PublishAsync(OutgoingMessage outgoingMessage, string queueName = QueueName.Outbox) { var message = CreateMessage(outgoingMessage); await bus.PublishAsync(Exchange.GetDefault(), queueName, false, message); }