Example #1
0
        public TestConventions(ITypeNameSerializer typeNameSerializer) : base(typeNameSerializer)
        {
            QueueNamingConvention = (messageType, subscriptionId) =>
            {
                var typeName = typeNameSerializer.Serialize(messageType);
                return string.Format("{0}_{1}", typeName, subscriptionId);
            };

        }
Example #2
0
        public Conventions(ITypeNameSerializer typeNameSerializer)
        {
            Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer");

            // Establish default conventions.
            ExchangeNamingConvention = messageType =>
            {
                var attr = GetQueueAttribute(messageType);

                return(string.IsNullOrEmpty(attr.ExchangeName)
                    ? typeNameSerializer.Serialize(messageType)
                    : attr.ExchangeName);
            };

            TopicNamingConvention = messageType => "";

            QueueNamingConvention =
                (messageType, subscriptionId) =>
            {
                var attr = GetQueueAttribute(messageType);

                if (string.IsNullOrEmpty(attr.QueueName))
                {
                    var typeName = typeNameSerializer.Serialize(messageType);

                    return(string.IsNullOrEmpty(subscriptionId)
                                ? typeName
                                : string.Format("{0}_{1}", typeName, subscriptionId));
                }

                return(string.IsNullOrEmpty(subscriptionId)
                            ? attr.QueueName
                            : string.Format("{0}_{1}", attr.QueueName, subscriptionId));
            };
            RpcRoutingKeyNamingConvention = typeNameSerializer.Serialize;

            ErrorQueueNamingConvention          = () => "EasyNetQ_Default_Error_Queue";
            ErrorExchangeNamingConvention       = info => "ErrorExchange_" + info.RoutingKey;
            RpcRequestExchangeNamingConvention  = (type) => "easy_net_q_rpc";
            RpcResponseExchangeNamingConvention = (type) => "easy_net_q_rpc";
            RpcReturnQueueNamingConvention      = () => "easynetq.response." + Guid.NewGuid();

            ConsumerTagConvention = () => Guid.NewGuid().ToString();
        }
Example #3
0
		public Conventions(ITypeNameSerializer typeNameSerializer)
		{
		    Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer");

		    // Establish default conventions.
            ExchangeNamingConvention = messageType =>
            {
                var attr = GetQueueAttribute(messageType);

                return string.IsNullOrEmpty(attr.ExchangeName)
                    ? typeNameSerializer.Serialize(messageType)
                    : attr.ExchangeName;
            };
			
            TopicNamingConvention = messageType => "";
			
            QueueNamingConvention =
					(messageType, subscriptionId) =>
					{
                        var attr = GetQueueAttribute(messageType);

                        if (string.IsNullOrEmpty(attr.QueueName))
                        {
                            var typeName = typeNameSerializer.Serialize(messageType);

                            return string.IsNullOrEmpty(subscriptionId)
                                ? typeName
                                : string.Format("{0}_{1}", typeName, subscriptionId);
                        }

                        return string.IsNullOrEmpty(subscriptionId)
                            ? attr.QueueName
                            : string.Format("{0}_{1}", attr.QueueName, subscriptionId);
					};
            RpcRoutingKeyNamingConvention = typeNameSerializer.Serialize;

            ErrorQueueNamingConvention = () => "EasyNetQ_Default_Error_Queue";
		    ErrorExchangeNamingConvention = info => "ErrorExchange_" + info.RoutingKey;
            RpcExchangeNamingConvention = () => "easy_net_q_rpc";
		    RpcReturnQueueNamingConvention = () => "easynetq.response." + Guid.NewGuid().ToString();

            ConsumerTagConvention = () => Guid.NewGuid().ToString();
		}
Example #4
0
        public async Task FuturePublishAsync <T>(
            DateTime futurePublishDate, T message, string topic, string cancellationKey = null
            ) where T : class
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var scheduleMeType     = typeof(ScheduleMe);
            var scheduleMeExchange = await exchangeDeclareStrategy
                                     .DeclareExchangeAsync(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        = topic
            };
            var easyNetQMessage = new Message <ScheduleMe>(scheduleMe)
            {
                Properties =
                {
                    DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(scheduleMeType)
                }
            };
            await advancedBus.PublishAsync(scheduleMeExchange, conventions.TopicNamingConvention(scheduleMeType), false,
                                           easyNetQMessage).ConfigureAwait(false);
        }
Example #5
0
        public virtual AckStrategy HandleConsumerError(ConsumerExecutionContext context, Exception exception)
        {
            Preconditions.CheckNotNull(context, "context");
            Preconditions.CheckNotNull(exception, "exception");

            if (disposed || disposing)
            {
                logger.ErrorFormat(
                    "ErrorStrategy was already disposed, when attempting to handle consumer error. Error message will not be published and message with receivedInfo={receivedInfo} will be requeed",
                    context.Info
                    );

                return(AckStrategies.NackWithRequeue);
            }

            try
            {
                Connect();

                using (var model = connection.CreateModel())
                {
                    var errorExchange = DeclareErrorExchangeQueueStructure(model, context);

                    var messageBody = CreateErrorMessage(context, exception);
                    var properties  = model.CreateBasicProperties();
                    properties.Persistent = true;
                    properties.Type       = typeNameSerializer.Serialize(typeof(Error));

                    model.BasicPublish(errorExchange, context.Info.RoutingKey, properties, messageBody);
                }
            }
            catch (BrokerUnreachableException unreachableException)
            {
                // thrown if the broker is unreachable duringe initial creation.
                logger.Error(
                    unreachableException,
                    "Cannot connect to broker while attempting to publish error message"
                    );
            }
            catch (OperationInterruptedException interruptedException)
            {
                // thrown if the broker connection is broken during declare or publish.
                logger.Error(
                    interruptedException,
                    "Broker connection was closed while attempting to publish error message"
                    );
            }
            catch (Exception unexpectedException)
            {
                // Something else unexpected has gone wrong :(
                logger.Error(unexpectedException, "Failed to publish error message");
            }

            return(AckStrategies.Ack);
        }
Example #6
0
        public CustomConventions(ITypeNameSerializer typeNameSerializer, string brokerId)
        {
            // Exchange naming convention: brokerId.Interface.MessageType
            ExchangeNamingConvention = messageType =>
            {
                var attr = GetQueueAttribute(messageType);

                return(string.IsNullOrEmpty(attr.ExchangeName)
                    ? $"{brokerId}.{typeof(T).Name}.{typeNameSerializer.Serialize(messageType)}"
                    : $"{brokerId}.{attr.ExchangeName}");
            };

            TopicNamingConvention = messageType => "";

            // Queue naming convention: brokerId.MessageType_SubscriptionId
            QueueNamingConvention = (messageType, subscriptionId) =>
            {
                var attr = GetQueueAttribute(messageType);

                if (!string.IsNullOrEmpty(attr.QueueName))
                {
                    return(string.IsNullOrEmpty(subscriptionId)
                        ? $"{brokerId}.{attr.QueueName}"
                        : $"{brokerId}.{attr.QueueName}_{subscriptionId}");
                }

                var typeName = typeNameSerializer.Serialize(messageType);

                return(string.IsNullOrEmpty(subscriptionId)
                    ? $"{brokerId}.{typeName}"
                    : $"{brokerId}.{typeName}_{subscriptionId}");
            };

            ErrorQueueNamingConvention    = () => $"{brokerId}.EasyNetQ_Default_Error_Queue";
            ErrorExchangeNamingConvention = info => $"{brokerId}.ErrorExchange_{info.RoutingKey}";

            RpcExchangeNamingConvention    = () => $"{brokerId}.RPC";
            RpcReturnQueueNamingConvention = () => $"{brokerId}.RPC.{Guid.NewGuid()}";
            RpcRoutingKeyNamingConvention  = type => $"{brokerId}.{typeof(T).Name}.{typeNameSerializer.Serialize(type)}";

            ConsumerTagConvention = () => Guid.NewGuid().ToString();
        }
Example #7
0
        /// <summary>
        ///     Creates Conventions
        /// </summary>
        public Conventions(ITypeNameSerializer typeNameSerializer)
        {
            Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer");

            ExchangeNamingConvention = type =>
            {
                var attr = GetQueueAttribute(type);

                return(string.IsNullOrEmpty(attr.ExchangeName)
                    ? typeNameSerializer.Serialize(type)
                    : attr.ExchangeName);
            };

            TopicNamingConvention = type => "";

            QueueNamingConvention = (type, subscriptionId) =>
            {
                var attr = GetQueueAttribute(type);

                if (string.IsNullOrEmpty(attr.QueueName))
                {
                    var typeName = typeNameSerializer.Serialize(type);

                    return(string.IsNullOrEmpty(subscriptionId)
                            ? typeName
                            : $"{typeName}_{subscriptionId}");
                }

                return(string.IsNullOrEmpty(subscriptionId)
                        ? attr.QueueName
                        : $"{attr.QueueName}_{subscriptionId}");
            };
            RpcRoutingKeyNamingConvention = typeNameSerializer.Serialize;

            ErrorQueueNamingConvention          = receivedInfo => "EasyNetQ_Default_Error_Queue";
            ErrorExchangeNamingConvention       = receivedInfo => "ErrorExchange_" + receivedInfo.RoutingKey;
            RpcRequestExchangeNamingConvention  = type => "easy_net_q_rpc";
            RpcResponseExchangeNamingConvention = type => "easy_net_q_rpc";
            RpcReturnQueueNamingConvention      = type => "easynetq.response." + Guid.NewGuid();

            ConsumerTagConvention = () => Guid.NewGuid().ToString();
        }
        public virtual AckStrategy HandleConsumerError(ConsumerExecutionContext context, Exception exception)
        {
            Preconditions.CheckNotNull(context, "context");
            Preconditions.CheckNotNull(exception, "exception");

            if (disposed || disposing)
            {
                logger.ErrorWrite(
                    "EasyNetQ Consumer Error Handler: DefaultConsumerErrorStrategy was already disposed, when attempting to handle consumer error.  This can occur when messaging is being shut down through disposal of the IBus.  Message will not be ackd to RabbitMQ server and will remain on the RabbitMQ queue.  Error message will not be published to error queue.\n" +
                    "ConsumerTag: {0}, DeliveryTag: {1}\n",
                    context.Info.ConsumerTag,
                    context.Info.DeliverTag);
                return(AckStrategies.NackWithRequeue);
            }

            try
            {
                Connect();

                using (var model = connection.CreateModel())
                {
                    var errorExchange = DeclareErrorExchangeQueueStructure(model, context);

                    var messageBody = CreateErrorMessage(context, exception);
                    var properties  = model.CreateBasicProperties();
                    properties.Persistent = true;
                    properties.Type       = typeNameSerializer.Serialize(typeof(Error));

                    model.BasicPublish(errorExchange, context.Info.RoutingKey, properties, messageBody);
                }
            }
            catch (BrokerUnreachableException)
            {
                // thrown if the broker is unreachable during initial creation.
                logger.ErrorWrite("EasyNetQ Consumer Error Handler cannot connect to Broker\n" +
                                  CreateConnectionCheckMessage());
            }
            catch (OperationInterruptedException interruptedException)
            {
                // thrown if the broker connection is broken during declare or publish.
                logger.ErrorWrite("EasyNetQ Consumer Error Handler: Broker connection was closed while attempting to publish Error message.\n" +
                                  string.Format("Exception was: '{0}'\n", interruptedException.Message) +
                                  CreateConnectionCheckMessage());
            }
            catch (Exception unexpectedException)
            {
                // Something else unexpected has gone wrong :(
                logger.ErrorWrite("EasyNetQ Consumer Error Handler: Failed to publish error message\nException is:\n"
                                  + unexpectedException);
            }
            return(AckStrategies.Ack);
        }
Example #9
0
        public virtual IDisposable Respond(Func <byte[], Task <byte[]> > responder, Action <IResponderConfiguration> configure, string queueName)
        {
            Preconditions.CheckNotNull(responder, "responder");
            Preconditions.CheckNotNull(configure, "configure");
            // We're explicitely validating TResponse here because the type won't be used directly.
            // It'll only be used when executing a successful responder, which will silently fail if TResponse serialized length exceeds the limit.
            Preconditions.CheckShortString(typeNameSerializer.Serialize(typeof(byte[])), "byte[]");

            //var requestType = typeof(byte[]);

            var configuration = new ResponderConfiguration(connectionConfiguration.PrefetchCount);

            configure(configuration);

            //var queue = advancedBus.QueueDeclare(queueName);
            var queue = new Queue(queueName, false);

            return(advancedBus.Consume(queue
                                       , (message, requestMessage, messageReceivedInfo) => ExecuteResponder(responder, message, requestMessage, messageReceivedInfo)
                                       , c => c.WithPrefetchCount(configuration.PrefetchCount)
                                       ));
        }
Example #10
0
        public SerializedMessage SerializeMessage(IMessage message)
        {
            var typeName          = typeNameSerializer.Serialize(message.MessageType);
            var messageBody       = serializer.MessageToBytes(message.GetBody());
            var messageProperties = message.Properties;

            messageProperties.Type = typeName;
            if (string.IsNullOrEmpty(messageProperties.CorrelationId))
            {
                messageProperties.CorrelationId = correlationIdGenerator.GetCorrelationId();
            }
            return(new SerializedMessage(messageProperties, messageBody));
        }
Example #11
0
        public SerializedMessage SerializeMessage <T>(IMessage <T> message) where T : class
        {
            var typeName          = typeNameSerializer.Serialize(message.Body.GetType());
            var messageBody       = serializer.MessageToBytes(message.Body);
            var messageProperties = message.Properties;

            messageProperties.Type = typeName;
            if (string.IsNullOrEmpty(messageProperties.CorrelationId))
            {
                messageProperties.CorrelationId = getCorrelationId();
            }

            return(new SerializedMessage(messageProperties, messageBody));
        }
Example #12
0
        public SerializedMessage SerializeMessage(IMessage message)
        {
            var str        = _typeNameSerializer.Serialize(message.MessageType);
            var bytes      = _serializer.MessageToBytes(message.MessageType, message.GetBody());
            var properties = message.Properties;

            properties.Type = str;

            if (_useCorrelationIds && string.IsNullOrEmpty(properties.CorrelationId))
            {
                properties.CorrelationId = _correlationIdGenerator.GetCorrelationId();
            }

            return(new SerializedMessage(properties, bytes));
        }
Example #13
0
        public Conventions(ITypeNameSerializer typeNameSerializer)
        {
            // Establish default conventions.
            ExchangeNamingConvention = messageType =>
            {
                var attr = GetQueueAttribute(messageType);

                return(string.IsNullOrEmpty(attr.ExchangeName)
                    ? typeNameSerializer.Serialize(messageType)
                    : attr.ExchangeName);
            };

            TopicNamingConvention = messageType => "";

            QueueNamingConvention =
                (messageType, subscriptionId) =>
            {
                var attr = GetQueueAttribute(messageType);

                if (string.IsNullOrEmpty(attr.QueueName))
                {
                    var typeName = typeNameSerializer.Serialize(messageType);

                    return(string.IsNullOrEmpty(subscriptionId)
                                ? typeName
                                : string.Format("{0}_{1}", typeName, subscriptionId));
                }

                return(string.IsNullOrEmpty(subscriptionId)
                            ? attr.QueueName
                            : string.Format("{0}_{1}", attr.QueueName, subscriptionId));
            };
            ErrorQueueNamingConvention    = () => "ZRabbitMq_Default_Error_Queue";
            ErrorExchangeNamingConvention = info => "ErrorExchange_" + info.RoutingKey;
            ConsumerTagConvention         = () => Guid.NewGuid().ToString();
        }
Example #14
0
        public Conventions(ITypeNameSerializer typeNameSerializer)
        {
            Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer");

            // Establish default conventions.
            this.TopicNamingConvention          = messageType => string.Empty;
            this.RpcRoutingKeyNamingConvention  = typeNameSerializer.Serialize;
            this.ErrorQueueNamingConvention     = () => "AzureNetQ_Default_Error_Queue";
            this.RpcReturnQueueNamingConvention = () => "azurenetq.response." + Guid.NewGuid();
            this.ConsumerTagConvention          = () => Guid.NewGuid().ToString();
            this.QueueNamingConvention          = messageType =>
            {
                var typeName = typeNameSerializer.Serialize(messageType);
                return(string.Format("{0}", typeName));
            };
        }
Example #15
0
        public Conventions(ITypeNameSerializer typeNameSerializer)
        {
            Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer");

            // Establish default conventions.
            this.TopicNamingConvention = messageType => string.Empty;
            this.RpcRoutingKeyNamingConvention = typeNameSerializer.Serialize;
            this.ErrorQueueNamingConvention = () => "AzureNetQ_Default_Error_Queue";
            this.RpcReturnQueueNamingConvention = () => "azurenetq.response." + Guid.NewGuid();
            this.ConsumerTagConvention = () => Guid.NewGuid().ToString();
            this.QueueNamingConvention = messageType =>
                {
                    var typeName = typeNameSerializer.Serialize(messageType);
                    return string.Format("{0}", typeName);
                };
        }
        private void SendMessageToErrorQueue(ConsumerExecutionContext context, Exception exception, IModel model, MessageProperties properties)
        {
            var errorExchange = DeclareErrorExchangeQueueStructure(model, context);

            _logger.InfoWrite(
                $"(DEAD LETTERED) Second Level Retry max reached for message of type [{properties.Type}], message is sent to dead letter queue: [{errorExchange}].");

            var messageBody = CreateDefaultErrorMessage(context, exception.InnerException);

            var errorProperties = model.CreateBasicProperties();

            properties.CopyTo(errorProperties);
            errorProperties.Persistent = true;
            errorProperties.Type       = _typeNameSerializer.Serialize(typeof(RabbitErrorMessage));

            model.BasicPublish(errorExchange, context.Info.RoutingKey, errorProperties, messageBody);
        }
Example #17
0
        public AckStrategy HandleConsumerError(ConsumerExecutionContext context, Exception exception)
        {
            if (!_disposed && !_disposing)
            {
                try
                {
                    var user = _userRepository.GetUserByLogQueueAsync(context.Info.Queue);
                    if (user == null)
                    {
                        _logger.LogWarning($"Can't get user by queue '{context.Info.Queue}'");
                        return(AckStrategies.Ack);
                    }

                    Connect();
                    using (var model = _connection.CreateModel())
                    {
                        var messageBody = CreateErrorMessage(context, exception);
                        var properties  = model.CreateBasicProperties();
                        properties.Persistent = true;
                        properties.Type       = _typeNameSerializer.Serialize(typeof(Error));

                        model.BasicPublish("errors", user.Username, false, properties, messageBody);

                        return(AckStrategies.Ack);
                    }
                }
                catch (BrokerUnreachableException unreachableException)
                {
                    _logger.LogError(unreachableException, "Cannot connect to broker while attempting to publish error message");
                }
                catch (OperationInterruptedException interruptedException)
                {
                    _logger.LogError(interruptedException, "Broker connection was closed while attempting to publish error message");
                }
                catch (Exception unexpectedException)
                {
                    _logger.LogError(unexpectedException, "Failed to publish error message");
                }
            }

            return(AckStrategies.NackWithRequeue);
        }
        public virtual PostExceptionAckStrategy HandleConsumerError(ConsumerExecutionContext context, Exception exception)
        {
            Preconditions.CheckNotNull(context, "context");
            Preconditions.CheckNotNull(exception, "exception");

            try
            {
                Connect();

                using (var model = connection.CreateModel())
                {
                    var errorExchange = DeclareErrorExchangeQueueStructure(model, context);

                    var messageBody = CreateErrorMessage(context, exception);
                    var properties  = model.CreateBasicProperties();
                    properties.SetPersistent(true);
                    properties.Type = typeNameSerializer.Serialize(typeof(Error));

                    model.BasicPublish(errorExchange, context.Info.RoutingKey, properties, messageBody);
                }
            }
            catch (BrokerUnreachableException)
            {
                // thrown if the broker is unreachable during initial creation.
                logger.ErrorWrite("EasyNetQ Consumer Error Handler cannot connect to Broker\n" +
                                  CreateConnectionCheckMessage());
            }
            catch (OperationInterruptedException interruptedException)
            {
                // thrown if the broker connection is broken during declare or publish.
                logger.ErrorWrite("EasyNetQ Consumer Error Handler: Broker connection was closed while attempting to publish Error message.\n" +
                                  string.Format("Message was: '{0}'\n", interruptedException.Message) +
                                  CreateConnectionCheckMessage());
            }
            catch (Exception unexpectedException)
            {
                // Something else unexpected has gone wrong :(
                logger.ErrorWrite("EasyNetQ Consumer Error Handler: Failed to publish error message\nException is:\n"
                                  + unexpectedException);
            }
            return(Consumer.PostExceptionAckStrategy.ShouldAck);
        }
Example #19
0
        public IspConventions(ITypeNameSerializer typeNameSerializer) : base(typeNameSerializer)
        {
            ExchangeNamingConvention = messageType =>
            {
                var attr = GetQueueAttribute(messageType);

                if (!string.IsNullOrEmpty(attr.ExchangeName))
                {
                    return(attr.ExchangeName);
                }

                if (messageType == typeof(EventDataOfOld))
                {
                    return(IspEventEntityAssemblyName);
                }
                else
                {
                    return(typeNameSerializer.Serialize(messageType));
                }
            };
        }
Example #20
0
        public virtual Task PublishAsync <T>(
            IExchange exchange,
            string routingKey,
            bool mandatory,
            bool immediate,
            IMessage <T> message) where T : class
        {
            Preconditions.CheckNotNull(exchange, "exchange");
            Preconditions.CheckShortString(routingKey, "routingKey");
            Preconditions.CheckNotNull(message, "message");

            var typeName    = typeNameSerializer.Serialize(message.Body.GetType());
            var messageBody = serializer.MessageToBytes(message.Body);

            message.Properties.Type          = typeName;
            message.Properties.CorrelationId =
                string.IsNullOrEmpty(message.Properties.CorrelationId) ?
                getCorrelationId() :
                message.Properties.CorrelationId;

            return(PublishAsync(exchange, routingKey, mandatory, immediate, message.Properties, messageBody));
        }
        /// <summary>
        /// Composes the outgoing audit message to RabbitMQ. The handler has its own internal audit log receiver, see the setyup function in the service host.
        /// </summary>
        /// <param name="rawMessage">The raw message from RabbitMQ.</param>
        /// <param name="direction">The direction, either incoming or outgoing.</param>
        private void SendAuditMessage(RawMessage rawMessage, Direction direction)
        {
            // Connect to Rabbit
            Connect();

            using (var model = _connection.CreateModel())
            {
                // Set the queue name, [handler]_audit and exchange.
                var consumer = GetConsumerProducerName().Replace(" ", "_");
                var queue    = $"{consumer}_audit";
                var exchange = $"AuditExchange_{consumer}";

                // Make sure we have an audit queue.
                CreatAuditQueue(model, queue, exchange);

                // Create the message and its properties. (this is the place to add stuff for auditing)
                var properties = model.CreateBasicProperties();
                properties.Persistent = true;
                properties.Type       = _typeNameSerializer.Serialize(typeof(RabbitAuditMessage));

                var message   = Encoding.UTF8.GetString(rawMessage.Body);
                var reference = GetReferenceCode(rawMessage.Properties.Type, message);

                var msg = _serializer.MessageToBytes(new RabbitAuditMessage
                {
                    ProducerName  = rawMessage.Properties.AppIdPresent ? rawMessage.Properties.AppId : "Unknown",
                    Direction     = direction,
                    CorrelationId = new Guid(rawMessage.Properties.CorrelationId),
                    Properties    = rawMessage.Properties,
                    Message       = message,
                    DateTime      = DateTime.UtcNow,
                    RunId         = _correlationPersister.RunId,
                    ReferenceCode = reference,
                });

                // Send the message
                model.BasicPublish(exchange, queue, properties, msg);
            }
        }
Example #22
0
        public Conventions(ITypeNameSerializer typeNameSerializer)
        {
            Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer");

            // Establish default conventions.
            ExchangeNamingConvention = typeNameSerializer.Serialize;
            TopicNamingConvention    = messageType => "";
            QueueNamingConvention    =
                (messageType, subscriptionId) =>
            {
                var typeName = typeNameSerializer.Serialize(messageType);
                return(string.Format("{0}_{1}", typeName, subscriptionId));
            };
            RpcRoutingKeyNamingConvention = typeNameSerializer.Serialize;

            ErrorQueueNamingConvention     = () => "EasyNetQ_Default_Error_Queue";
            ErrorExchangeNamingConvention  = (originalRoutingKey) => "ErrorExchange_" + originalRoutingKey;
            RpcExchangeNamingConvention    = () => "easy_net_q_rpc";
            RpcReturnQueueNamingConvention = () => "easynetq.response." + Guid.NewGuid().ToString();

            ConsumerTagConvention = () => Guid.NewGuid().ToString();
        }
Example #23
0
        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 easyNetQMessage = new Message <ScheduleMe>(new ScheduleMe
                {
                    WakeTime = futurePublishDate,
                    BindingKey = typeName,
                    CancellationKey = cancellationKey,
                    InnerMessage = messageBody
                })
                {
                    Properties = { DeliveryMode = (byte)(messageDeliveryModeStrategy.IsPersistent(messageType) ? 2 : 1) }
                };
                return advancedBus.PublishAsync(exchange, conventions.TopicNamingConvention(messageType), false, false, easyNetQMessage);
            }));
        }
Example #24
0
        public virtual IDisposable Respond <TRequest, TResponse>(Func <TRequest, Task <TResponse> > responder, Action <IResponderConfiguration> configure) where TRequest : class where TResponse : class
        {
            Preconditions.CheckNotNull(responder, "responder");
            Preconditions.CheckNotNull(configure, "configure");
            // We're explicitely validating TResponse here because the type won't be used directly.
            // It'll only be used when executing a successful responder, which will silently fail if TResponse serialized length exceeds the limit.
            Preconditions.CheckShortString(typeNameSerializer.Serialize(typeof(TResponse)), "TResponse");

            var configuration = new ResponderConfiguration(connectionConfiguration.PrefetchCount);

            configure(configuration);

            var routingKey = conventions.RpcRoutingKeyNamingConvention(typeof(TRequest));

            var exchange = advancedBus.ExchangeDeclare(conventions.RpcExchangeNamingConvention(), ExchangeType.Direct);
            var queue    = advancedBus.QueueDeclare(routingKey);

            advancedBus.Bind(exchange, queue, routingKey);

            return(advancedBus.Consume <TRequest>(queue, (requestMessage, messageRecievedInfo) => ExecuteResponder(responder, requestMessage),
                                                  c => c.WithPrefetchCount(configuration.PrefetchCount)));
        }
        public SerializedMessage SerializeMessage(IMessage message)
        {
            var messageBody       = message.GetBody();
            var messageProperties = message.Properties;

            _bindingCache.GetOrAdd(message.MessageType, ScanForBindings)
            .ForEach(binding => binding.ToMessageMetaData(messageBody, messageProperties));

            // The remainder of this method duplicates the behaviour of the default EasyNetQ message serialization
            // strategy (it would be wonderful if we could just wrap it with a decorator)...
            var typeName = _typeNameSerializer.Serialize(message.MessageType);

            messageProperties.Type = typeName;

            if (String.IsNullOrEmpty(messageProperties.CorrelationId))
            {
                messageProperties.CorrelationId = _correlationIdGenerator.GetCorrelationId();
            }

            var messageBytes = _serializer.MessageToBytes(messageBody);

            return(new SerializedMessage(messageProperties, messageBytes));
        }
        public Task FuturePublishAsync <T>(DateTime futurePublishDate, T message, string cancellationKey = null) where T : class
        {
            Preconditions.CheckNotNull(message, "message");
            var scheduleMeType = typeof(ScheduleMe);

            return(publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, scheduleMeType, ExchangeType.Topic).Then(scheduleMeExchange =>
            {
                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)
                    }
                };
                return advancedBus.PublishAsync(scheduleMeExchange, conventions.TopicNamingConvention(scheduleMeType), false, false, easyNetQMessage);
            }));
        }
Example #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="typeNameSerializer"></param>
        public SheshaMQConventions(ITypeNameSerializer typeNameSerializer) : base(typeNameSerializer)
        {
            QueueNamingConvention = (messageType, id) =>
            {
                var attr = GetQueueAttribute(messageType);

                if (!string.IsNullOrEmpty(attr.QueueName))
                {
                    var systemName = id.Split(':').FirstOrDefault();
                    systemName = string.Concat(systemName.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString()));
                    return($"{attr.QueueName}_{systemName.ToLower()}");
                }
                return(base.QueueNamingConvention.Invoke(messageType, id));
            };
            ExchangeNamingConvention = messageType =>
            {
                var attr         = GetQueueAttribute(messageType);
                var settings     = StaticContext.IocManager.Resolve <ISheshaSettings>();
                var exchangeName = string.IsNullOrEmpty(settings.ExchangeName) ? typeNameSerializer.Serialize(messageType) : settings.ExchangeName;
                return(string.IsNullOrEmpty(attr.ExchangeName)
                    ? (exchangeName)
                    : attr.ExchangeName);
            };
        }
Example #28
0
        public void Should_serialize_hashset_of_string_type()
        {
            var typeName = typeNameSerializer.Serialize(typeof(HashSet <string>));

            typeName.ShouldEqual("System.Collections.Generic.HashSet`1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]:System.Collections");
        }
        public void Should_serialize_hashset_of_string_type()
        {
            var typeName = typeNameSerializer.Serialize(typeof(HashSet <string>));

            typeName.Should().Be("System.Collections.Generic.HashSet`1[[System.String, System.Private.CoreLib]], System.Collections");
        }
Example #30
0
        /// <summary>
        /// 消费异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public AckStrategy HandleConsumerError(ConsumerExecutionContext context, Exception exception)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            if (disposed || disposing)
            {
                _logger.LogError(
                    "ErrorStrategy was already disposed, when attempting to handle consumer error. Error message will not be published and message with receivedInfo={receivedInfo} will be requeued",
                    context.Info
                    );

                return(AckStrategies.NackWithRequeue);
            }

            try
            {
                Connect();
                _logger.LogError($"消费类型为{context.Properties.Type ?? "UnKown"}的消息时出现异常 {exception.ToString()}");
                using (var model = connection.CreateModel())
                {
                    try
                    {
                        var temp = context.Properties.Headers["ReTryCount"];
                        if ((int)temp >= 5)
                        {
                            //进入失败队列,不重试
                            var failedExchange   = DeclareFailedExchangeWithQueue(model, context);
                            var failedProperties = model.CreateBasicProperties();
                            failedProperties.Persistent = true;
                            failedProperties.Type       = context.Properties.Type == null?typeNameSerializer.Serialize(typeof(Object)) : context.Properties.Type;

                            var failedRoutingKey = string.IsNullOrEmpty(context.Info.RoutingKey) ? context.Info.Queue.Substring(context.Info.Exchange.Length + 1) : context.Info.RoutingKey;
                            model.BasicPublish(failedExchange, failedRoutingKey, failedProperties, context.Body);
                            return(AckStrategies.Ack);
                        }
                        else
                        {
                            context.Properties.Headers["ReTryCount"] = (int)context.Properties.Headers["ReTryCount"] + 1;
                        }
                    }
                    catch (Exception e)
                    {
                        context.Properties.Headers.Add("ReTryCount", 1);
                    }
                    //进入死信队列,进行重试
                    var errorExchange = DeclareReTryExchangeWithQueue(model, context);
                    var messageBody   = context.Body; //CreateErrorMessage(context, exception);
                    var properties    = model.CreateBasicProperties();
                    properties.Persistent = true;
                    properties.Type       = context.Properties.Type == null?typeNameSerializer.Serialize(typeof(Object)) : context.Properties.Type;

                    properties.Headers = context.Properties.Headers;
                    var errorRoutingKey = string.IsNullOrEmpty(context.Info.RoutingKey) ? context.Info.Queue.Substring(context.Info.Exchange.Length + 1) : context.Info.RoutingKey;
                    model.BasicPublish(errorExchange, errorRoutingKey, properties, messageBody);
                    return(AckStrategies.Ack);
                }
            }
            catch (BrokerUnreachableException unreachableException)
            {
                _logger.LogError($"Cannot connect to broker while attempting to publish error message {unreachableException.ToString()}");
            }
            catch (OperationInterruptedException interruptedException)
            {
                _logger.LogError($"Broker connection was closed while attempting to publish error message {interruptedException.ToString()}");
            }
            catch (Exception unexpectedException)
            {
                _logger.LogError($"Failed to publish error message {unexpectedException.ToString()}");
            }
            return(AckStrategies.NackWithRequeue);
        }
Example #31
0
 public object BytesToMessage(Type type, byte[] bytes)
 {
     return(typeof(IMessage).IsAssignableFrom(type)
         ? BytesToMessage(_typeNameSerializer.Serialize(type), bytes)
         : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bytes), type, _serializerSettings));
 }
Example #32
0
        public void Should_serialize_a_type_name()
        {
            var typeName = typeNameSerializer.Serialize(typeof(string));

            typeName.ShouldEqual(expectedTypeName);
        }
Example #33
0
        public void The_default_exchange_naming_convention_should_use_the_TypeNameSerializers_Serialize_method()
        {
            var result = conventions.ExchangeNamingConvention(typeof(TestMessage));

            result.Should().Be(typeNameSerializer.Serialize(typeof(TestMessage)));
        }