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);
                }
            }
        }
Beispiel #2
0
 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)
         }
     };
 }
Beispiel #3
0
        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;
        }
Beispiel #5
0
 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;
        }
Beispiel #7
0
        // -------------------------------- 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));
        }
Beispiel #11
0
        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);
        }
Beispiel #12
0
        // -------------------------------- 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());
        }
Beispiel #13
0
 public Message()
 {
     Body        = default;
     Properties  = new MessageProperties();
     MessageType = typeof(T);
 }
Beispiel #14
0
 public Message(T body)
 {
     Body        = body;
     Properties  = new MessageProperties();
     MessageType = body != null?body.GetType() : typeof(T);
 }
Beispiel #15
0
        /// <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
                    );
            }
        }
Beispiel #16
0
        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);
        }
Beispiel #17
0
        /// <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);
        }
Beispiel #18
0
 public SerializedMessage(MessageProperties properties, byte[] messageBody)
 {
     Properties = properties;
     Body       = messageBody;
 }
Beispiel #19
0
 public Message(T body, MessageProperties properties)
 {
     Body        = body;
     Properties  = properties;
     MessageType = body != null?body.GetType() : typeof(T);
 }
Beispiel #20
0
        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);
            }
        }
Beispiel #21
0
        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
                    );
            }
        }
Beispiel #22
0
        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);
        }
Beispiel #23
0
 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 => { });
 }
Beispiel #25
0
        // -------------------------------- 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
                    );
            }
        }
Beispiel #26
0
        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;
        }
Beispiel #27
0
        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);
        }
 public SerializedMessage(MessageProperties properties, byte[] messageBody)
 {
     Properties = properties;
     Body = messageBody;
 }