public IEnumerable<RecoveryMessage> GetMessagesFromQueue(IQueueOptions options) { using (var connection = RabbitConnection.FromOptions(options)) using (var channel = connection.CreateModel()) { try { channel.QueueDeclarePassive(options.ErrorQueueName); } catch (OperationInterruptedException exception) { _log.ErrorFormat("Error Occurred Getting a message from queue because {0}", exception, exception.Message); yield break; } var count = 0; while (count++ < options.MaxNumberOfMessagesToRetrieve) { var basicGetResult = channel.BasicGet(options.ErrorQueueName, noAck: options.RequireHandshake); if (basicGetResult == null) break; // no more messages on the queue var properties = new MessageProperties(basicGetResult.BasicProperties); var info = new MessageReceivedInfo( "recoveries", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, options.ErrorQueueName); yield return new RecoveryMessage(Encoding.UTF8.GetString(basicGetResult.Body), properties, info); } } }
public Error MapMessageToErrorSchema(AggregateException exception, string correlationId, string messageType, string payload, MessageProperties properties, IDictionary<string, object> headers, MessageReceivedInfo info) { return new Error { errorDateTime = DateTime.Now, errorType = ErrorTypeEnum.ApplicationError, component = exception.InnerException.Source, server = Environment.MachineName, serviceName = messageType, summary = exception.InnerException.Message, detail = exception.InnerException.StackTrace, original = new OriginalDetails { jobId = correlationId, exchangeName = (info == null) ? string.Empty : info.Exchange, queueName = (info == null) ? string.Empty : info.Queue, payload = payload, correlationId = correlationId, routingKey = (info == null) ? string.Empty : info.RoutingKey, deliveryMode = properties.DeliveryMode.ToString(), headers = ConvertDictionaryToHeaderDetails(headers), headerProperties = ConvertMessagePropertiesToHeaderDetails(properties) } }; }
public static IMessage CreateInstance(Type messageType, object body, MessageProperties properties) { Preconditions.CheckNotNull(messageType, "messageType"); Preconditions.CheckNotNull(body, "body"); Preconditions.CheckNotNull(properties, "properties"); var genericType = _genericMessageTypesMap.GetOrAdd(messageType, t => typeof(Message<>).MakeGenericType(messageType)); var message = ReflectionHelpers.CreateInstance(genericType, body, properties); return (IMessage)message; }
public MessageReturnedEventArgs(byte[] messageBody, MessageProperties messageProperties, MessageReturnedInfo messageReturnedInfo) { Preconditions.CheckNotNull(messageBody, "messageBody"); Preconditions.CheckNotNull(messageProperties, "messageProperties"); Preconditions.CheckNotNull(messageReturnedInfo, "messageReturnedInfo"); MessageBody = messageBody; MessageProperties = messageProperties; MessageReturnedInfo = messageReturnedInfo; }
private static HeaderDetails[] ConvertMessagePropertiesToHeaderDetails(MessageProperties properties) { return properties.GetType().GetProperties() .Where(_ => _.Name != "Headers" && properties.GetType().GetProperty(_.Name).GetValue(properties, null) != null) .Select(property => new HeaderDetails { key = property.Name, value = properties.GetType().GetProperty(property.Name).GetValue(properties, null).ToString() }).ToArray(); }
public RecoveryMessage(string body, MessageProperties properties, MessageReceivedInfo info) { if (body == null) throw new ArgumentNullException("body"); if (properties == null) throw new ArgumentNullException("properties"); if (info == null) throw new ArgumentNullException("info"); Body = body; Properties = properties; Info = info; }
// -------------------------------- publish --------------------------------------------- public void Publish( IExchange exchange, string routingKey, bool mandatory, bool immediate, MessageProperties messageProperties, byte[] body) { try { PublishAsync(exchange, routingKey, mandatory, immediate, messageProperties, body).Wait(); } catch (AggregateException aggregateException) { throw aggregateException.InnerException; } }
/// <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 void CheckMessageType <TMessage>( Byte[] body, MessageProperties properties, MessageReceivedInfo messageReceivedInfo) { Preconditions.CheckNotNull(body, "body"); Preconditions.CheckNotNull(properties, "properties"); Preconditions.CheckNotNull(messageReceivedInfo, "messageReceivedInfo"); var typeName = serializeType(typeof(TMessage)); if (properties.Type != typeName) { logger.ErrorWrite("Message type is incorrect. Expected '{0}', but was '{1}'", typeName, properties.Type); throw new EasyNetQInvalidMessageTypeException("Message type is incorrect. Expected '{0}', but was '{1}'", typeName, properties.Type); } }
public void Should_be_able_to_serialize_basic_properties() { var originalProperties = new BasicProperties { AppId = "some app id", ClusterId = "cluster id", ContentEncoding = "content encoding", CorrelationId = "correlation id", DeliveryMode = 4, Expiration = "expiration", MessageId = "message id", Priority = 1, ReplyTo = "abc", Timestamp = new AmqpTimestamp(123344044), Type = "Type", UserId = "user id", Headers = new Dictionary<string, object> { {"one", "header one"}, {"two", "header two"} } }; var messageBasicProperties = new MessageProperties(originalProperties); var binaryMessage = serializer.MessageToBytes(messageBasicProperties); var deserializedMessageBasicProperties = serializer.BytesToMessage<MessageProperties>(binaryMessage); var newProperties = new BasicProperties(); deserializedMessageBasicProperties.CopyTo(newProperties); Func<BasicProperties, string> getPropertiesString = p => { var builder = new StringBuilder(); p.AppendPropertyDebugStringTo(builder); return builder.ToString(); }; Assert.AreEqual(getPropertiesString(originalProperties), getPropertiesString(newProperties)); }
protected virtual async Task RequestPublishAsync <TRequest>( TRequest request, string routingKey, string returnQueueName, string correlationId, TimeSpan expiration, byte?priority, bool mandatory, CancellationToken cancellationToken ) { var requestType = typeof(TRequest); var exchange = await exchangeDeclareStrategy.DeclareExchangeAsync( conventions.RpcRequestExchangeNamingConvention(requestType), ExchangeType.Direct, cancellationToken ).ConfigureAwait(false); var properties = new MessageProperties { ReplyTo = returnQueueName, CorrelationId = correlationId, DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(requestType) }; if (expiration != Timeout.InfiniteTimeSpan) { properties.Expiration = expiration.TotalMilliseconds.ToString(CultureInfo.InvariantCulture); } if (priority != null) { properties.Priority = priority.Value; } var requestMessage = new Message <TRequest>(request, properties); await advancedBus.PublishAsync(exchange, routingKey, mandatory, requestMessage, cancellationToken) .ConfigureAwait(false); }
// -------------------------------- publish --------------------------------------------- public virtual Task PublishAsync( IExchange exchange, string routingKey, bool mandatory, bool immediate, MessageProperties messageProperties, byte[] body) { Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckShortString(routingKey, "routingKey"); Preconditions.CheckNotNull(messageProperties, "messageProperties"); Preconditions.CheckNotNull(body, "body"); var rawMessage = produceConsumeInterceptor.OnProduce(new RawMessage(messageProperties, body)); return(clientCommandDispatcher.Invoke(x => { var properties = x.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); return publisher.Publish(x, m => m.BasicPublish(exchange.Name, routingKey, mandatory, immediate, properties, rawMessage.Body)) .Then(() => logger.DebugWrite("Published to exchange: '{0}', routing key: '{1}', correlationId: '{2}'", exchange.Name, routingKey, messageProperties.CorrelationId)); }).Unwrap()); }
public Message() { Body = default; Properties = new MessageProperties(); MessageType = typeof(T); }
public Message(T body) { Body = body; Properties = new MessageProperties(); MessageType = body != null?body.GetType() : typeof(T); }
/// <inheritdoc /> public virtual async Task PublishAsync( IExchange exchange, string routingKey, bool mandatory, MessageProperties messageProperties, byte[] body, CancellationToken cancellationToken ) { Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckShortString(routingKey, "routingKey"); Preconditions.CheckNotNull(messageProperties, "messageProperties"); Preconditions.CheckNotNull(body, "body"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); var rawMessage = produceConsumeInterceptor.OnProduce(new ProducedMessage(messageProperties, body)); if (configuration.PublisherConfirms) { while (true) { var pendingConfirmation = await clientCommandDispatcher.InvokeAsync(model => { var confirmation = confirmationListener.CreatePendingConfirmation(model); rawMessage.Properties.SetConfirmationId(confirmation.Id); var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); try { model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); } catch (Exception) { confirmation.Cancel(); throw; } return(confirmation); }, ChannelDispatchOptions.PublishWithConfirms, cts.Token).ConfigureAwait(false); try { await pendingConfirmation.WaitAsync(cts.Token).ConfigureAwait(false); break; } catch (PublishInterruptedException) { } } } else { await clientCommandDispatcher.InvokeAsync(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); }, ChannelDispatchOptions.Publish, cts.Token).ConfigureAwait(false); } eventBus.Publish(new PublishedMessageEvent(exchange.Name, routingKey, rawMessage.Properties, rawMessage.Body)); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Published to exchange {exchange} with routingKey={routingKey} and correlationId={correlationId}", exchange.Name, routingKey, messageProperties.CorrelationId ); } }
public object Clone() { var copy = new MessageProperties(); if (contentTypePresent) { copy.ContentType = ContentType; } if (contentEncodingPresent) { copy.ContentEncoding = ContentEncoding; } if (deliveryModePresent) { copy.DeliveryMode = DeliveryMode; } if (priorityPresent) { copy.Priority = Priority; } if (correlationIdPresent) { copy.CorrelationId = CorrelationId; } if (replyToPresent) { copy.ReplyTo = ReplyTo; } if (expirationPresent) { copy.Expiration = Expiration; } if (messageIdPresent) { copy.MessageId = MessageId; } if (timestampPresent) { copy.Timestamp = Timestamp; } if (typePresent) { copy.Type = Type; } if (userIdPresent) { copy.UserId = UserId; } if (appIdPresent) { copy.AppId = AppId; } if (clusterIdPresent) { copy.ClusterId = ClusterId; } if (headersPresent) { copy.Headers = new Dictionary <string, object>(Headers); } return(copy); }
/// <inheritdoc /> public object Clone() { var copy = new MessageProperties(); if (contentTypePresent) { copy.ContentType = contentType; } if (contentEncodingPresent) { copy.ContentEncoding = contentEncoding; } if (deliveryModePresent) { copy.DeliveryMode = deliveryMode; } if (priorityPresent) { copy.Priority = priority; } if (correlationIdPresent) { copy.CorrelationId = correlationId; } if (replyToPresent) { copy.ReplyTo = replyTo; } if (expirationPresent) { copy.Expiration = expiration; } if (messageIdPresent) { copy.MessageId = messageId; } if (timestampPresent) { copy.Timestamp = timestamp; } if (typePresent) { copy.Type = type; } if (userIdPresent) { copy.UserId = userId; } if (appIdPresent) { copy.AppId = appId; } if (clusterIdPresent) { copy.ClusterId = clusterId; } if (headers != null && headers.Count > 0) { copy.headers = new Dictionary <string, object>(headers); } return(copy); }
public SerializedMessage(MessageProperties properties, byte[] messageBody) { Properties = properties; Body = messageBody; }
public Message(T body, MessageProperties properties) { Body = body; Properties = properties; MessageType = body != null?body.GetType() : typeof(T); }
public virtual void Publish(IExchange exchange, string routingKey, MessageProperties properties, byte[] messageBody, Action <IAdvancedPublishConfiguration> configure) { if (exchange == null) { throw new ArgumentNullException("exchange"); } if (routingKey == null) { throw new ArgumentNullException("routingKey"); } if (properties == null) { throw new ArgumentNullException("properties"); } if (messageBody == null) { throw new ArgumentNullException("messageBody"); } if (configure == null) { throw new ArgumentNullException("configure"); } if (disposed) { throw new EasyNetQException("PublishChannel is already disposed"); } if (!advancedBus.Connection.IsConnected) { throw new EasyNetQException("Publish failed. No rabbit server connected."); } try { var configuration = new AdvancedPublishConfiguration(); configure(configuration); if (publisherConfirms != null) { if (configuration.SuccessCallback == null || configuration.FailureCallback == null) { throw new EasyNetQException("When pulisher confirms are on, you must supply success and failure callbacks in the publish configuration"); } publisherConfirms.RegisterCallbacks(channel, configuration.SuccessCallback, configuration.FailureCallback); } var defaultProperties = channel.CreateBasicProperties(); properties.CopyTo(defaultProperties); exchange.Visit(new TopologyBuilder(channel)); channel.BasicPublish( exchange.Name, // exchange routingKey, // routingKey defaultProperties, // basicProperties messageBody); // body advancedBus.Logger.DebugWrite("Published to exchange: '{0}', routing key: '{1}', correlationId: '{2}'", exchange.Name, routingKey, defaultProperties.CorrelationId); } catch (OperationInterruptedException exception) { throw new EasyNetQException("Publish Failed: '{0}'", exception.Message); } catch (System.IO.IOException exception) { throw new EasyNetQException("Publish Failed: '{0}'", exception.Message); } }
public virtual async Task PublishAsync( IExchange exchange, string routingKey, bool mandatory, MessageProperties messageProperties, byte[] body) { Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckShortString(routingKey, "routingKey"); Preconditions.CheckNotNull(messageProperties, "messageProperties"); Preconditions.CheckNotNull(body, "body"); // Fix me: It's very hard now to move publish logic to separate abstraction, just leave it here. var rawMessage = produceConsumeInterceptor.OnProduce(new RawMessage(messageProperties, body)); if (connectionConfiguration.PublisherConfirms) { var timeout = TimeBudget.Start(connectionConfiguration.GetTimeout()); while (true) { if (timeout.IsExpired()) { throw new TimeoutException($"Publish timed out after {connectionConfiguration.Timeout} seconds"); } var confirmsWaiter = await clientCommandDispatcher.InvokeAsync(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); var waiter = confirmationListener.GetWaiter(model); try { model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); } catch (Exception) { waiter.Cancel(); throw; } return(waiter); }).ConfigureAwait(false); try { await confirmsWaiter.WaitAsync(timeout).ConfigureAwait(false); break; } catch (PublishInterruptedException) { } } } else { await clientCommandDispatcher.InvokeAsync(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); }).ConfigureAwait(false); } eventBus.Publish(new PublishedMessageEvent(exchange.Name, routingKey, rawMessage.Properties, rawMessage.Body)); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Published to exchange {exchange} with routingKey={routingKey} and correlationId={correlationId}", exchange.Name, routingKey, messageProperties.CorrelationId ); } }
public virtual void Consume(IQueue queue, Func <Byte[], MessageProperties, MessageReceivedInfo, Task> onMessage) { Preconditions.CheckNotNull(queue, "queue"); Preconditions.CheckNotNull(onMessage, "onMessage"); if (disposed) { throw new EasyNetQException("This bus has been disposed"); } var newConsumerTag = conventions.ConsumerTagConvention(); var subscriptionAction = new SubscriptionAction(newConsumerTag, logger, queue.IsSingleUse, queue.IsExclusive); subscriptionAction.Action = (isNewConnection) => { // recreate channel if current channel is no longer open or connection was dropped and reconnected (to survive server restart) if (subscriptionAction.Channel == null || subscriptionAction.Channel.IsOpen == false || isNewConnection) { subscriptionAction.Channel = CreateChannel(queue); } var channel = subscriptionAction.Channel; channel.BasicQos(0, connectionConfiguration.PrefetchCount, false); var consumer = consumerFactory.CreateConsumer(subscriptionAction, channel, queue.IsSingleUse, (consumerTag, deliveryTag, redelivered, exchange, routingKey, properties, body) => { var messageRecievedInfo = new MessageReceivedInfo { ConsumerTag = consumerTag, DeliverTag = deliveryTag, Redelivered = redelivered, Exchange = exchange, RoutingKey = routingKey }; var messsageProperties = new MessageProperties(properties); return(onMessage(body, messsageProperties, messageRecievedInfo)); }); var cancelNotifications = consumer as IConsumerCancelNotifications; if (cancelNotifications != null) { cancelNotifications.BasicCancel += OnBasicCancel; } channel.BasicConsume( queue.Name, // queue NoAck, // noAck consumer.ConsumerTag, // consumerTag consumer); // consumer logger.DebugWrite("Declared Consumer. queue='{0}', consumer tag='{1}' prefetchcount={2}", queue.Name, consumer.ConsumerTag, connectionConfiguration.PrefetchCount); }; AddSubscriptionAction(subscriptionAction); }
public void SetProperties(MessageProperties properties) { Preconditions.CheckNotNull(properties, "properties"); Properties = properties; }
public virtual void Publish(IExchange exchange, string routingKey, MessageProperties properties, byte[] messageBody) { Publish(exchange, routingKey, properties, messageBody, configuration => { }); }
// -------------------------------- publish --------------------------------------------- public void Publish( IExchange exchange, string routingKey, bool mandatory, MessageProperties messageProperties, byte[] body) { // Fix me: It's very hard now to move publish logic to separate abstraction, just leave it here. var rawMessage = produceConsumeInterceptor.OnProduce(new RawMessage(messageProperties, body)); if (connectionConfiguration.PublisherConfirms) { var timeout = TimeBudget.Start(TimeSpan.FromSeconds(connectionConfiguration.Timeout)); while (!timeout.IsExpired()) { var confirmsWaiter = clientCommandDispatcher.Invoke(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); var waiter = confirmationListener.GetWaiter(model); try { model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); } catch (Exception) { waiter.Cancel(); throw; } return(waiter); }); try { confirmsWaiter.Wait(timeout); break; } catch (PublishInterruptedException) { } } } else { clientCommandDispatcher.Invoke(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); }); } eventBus.Publish(new PublishedMessageEvent(exchange.Name, routingKey, rawMessage.Properties, rawMessage.Body)); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Published to exchange {exchange} with routingKey={routingKey} and correlationId={correlationId}", exchange.Name, routingKey, messageProperties.CorrelationId ); } }
public object Clone() { var copy = new MessageProperties(); if (contentTypePresent) copy.ContentType = ContentType; if (contentEncodingPresent) copy.ContentEncoding = ContentEncoding; if (deliveryModePresent) copy.DeliveryMode = DeliveryMode; if (priorityPresent) copy.Priority = Priority; if (correlationIdPresent) copy.CorrelationId = CorrelationId; if (replyToPresent) copy.ReplyTo = ReplyTo; if (expirationPresent) copy.Expiration = Expiration; if (messageIdPresent) copy.MessageId = MessageId; if (timestampPresent) copy.Timestamp = Timestamp; if (typePresent) copy.Type = Type; if (userIdPresent) copy.UserId = UserId; if (appIdPresent) copy.AppId = AppId; if (clusterIdPresent) copy.ClusterId = ClusterId; if (headersPresent) { copy.Headers = new Dictionary<string, object>(Headers); } return copy; }
public virtual async Task PublishAsync( IExchange exchange, string routingKey, bool mandatory, MessageProperties messageProperties, byte[] body) { Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckShortString(routingKey, "routingKey"); Preconditions.CheckNotNull(messageProperties, "messageProperties"); Preconditions.CheckNotNull(body, "body"); // Fix me: It's very hard now to move publish logic to separate abstraction, just leave it here. var rawMessage = produceConsumeInterceptor.OnProduce(new RawMessage(messageProperties, body)); if (connectionConfiguration.PublisherConfirms) { var timeBudget = new TimeBudget(TimeSpan.FromSeconds(connectionConfiguration.Timeout)).Start(); while (!timeBudget.IsExpired()) { var confirmsWaiter = await clientCommandDispatcher.InvokeAsync(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); var waiter = confirmationListener.GetWaiter(model); try { model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); } catch (Exception) { waiter.Cancel(); throw; } return(waiter); }).ConfigureAwait(false); try { await confirmsWaiter.WaitAsync(timeBudget.GetRemainingTime()).ConfigureAwait(false); break; } catch (PublishInterruptedException) { } } } else { await clientCommandDispatcher.InvokeAsync(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); }).ConfigureAwait(false); } eventBus.Publish(new PublishedMessageEvent(exchange.Name, routingKey, rawMessage.Properties, rawMessage.Body)); logger.DebugWrite("Published to exchange: '{0}', routing key: '{1}', correlationId: '{2}'", exchange.Name, routingKey, messageProperties.CorrelationId); }