示例#1
0
        private IModel CreateChannel(IQueue queue)
        {
            var channel = connection.CreateModel();

            channel.ModelShutdown += (model, reason) => logger.DebugWrite("Model Shutdown for queue: '{0}'", queue.Name);
            return(channel);
        }
示例#2
0
        private void Publish <T>(T @event)
        {
            var policy = Policy.Handle <BrokerUnreachableException>()
                         .Or <SocketException>()
                         .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                _logger.LogWarning(ex.ToString());
            });

            using (var channel = _persistentConnection.CreateModel())
            {
                var eventName = @event.GetType().Name;

                channel.ExchangeDeclare(exchange: BROKER_NAME, type: "direct");

                var message = JsonConvert.SerializeObject(@event);
                var body    = Encoding.UTF8.GetBytes(message);

                policy.Execute(() =>
                {
                    channel.BasicPublish(exchange: BROKER_NAME,
                                         routingKey: eventName,
                                         basicProperties: null,
                                         body: body);
                });
            }
        }
示例#3
0
        public async void Publish(IntegrationEvent @event)
        {
            ConnectToBroker();
            var policy = CreateRetryPolicy(@event);

            var eventName = @event.GetType().Name;

            using (var channel = PersistentConnection.CreateModel())
            {
                var message = JsonConvert.SerializeObject(@event);
                var body    = Encoding.UTF8.GetBytes(message);

                await policy.ExecuteAsync(() =>
                {
                    var properties          = channel.CreateBasicProperties();
                    properties.DeliveryMode = PERSISTENT_MODE;

                    Logger.LogTrace("Publicando evento no RabbitMQ: {EventId}", @event.Id);

                    channel.BasicPublish(
                        exchange: CENSUS_EXCHANGE,
                        routingKey: eventName,
                        mandatory: true,
                        basicProperties: properties,
                        body: body);

                    return(Task.CompletedTask);
                });
            }
        }
示例#4
0
        public void Publish(IntegrationEvent @event)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            var policy = Policy.Handle <Exception>()
                         .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                       (ex, time) => { Log.ForContext <QueueProvider>().Warning(ex, "{@ex}"); });

            using (var channel = _persistentConnection.CreateModel())
            {
                var eventName = @event.GetType()
                                .Name;

                channel.ExchangeDeclare(BROKER_NAME,
                                        "direct");

                var message = JsonConvert.SerializeObject(@event);
                var body    = Encoding.UTF8.GetBytes(message);

                policy.Execute(() =>
                {
                    var properties          = channel.CreateBasicProperties();
                    properties.DeliveryMode = 2;
                    channel.BasicPublish(BROKER_NAME,
                                         eventName,
                                         true,
                                         properties,
                                         body);
                });
            }
        }
示例#5
0
        public When_an_action_is_performed_on_a_closed_channel_that_then_opens()
        {
            persistentConnection = Substitute.For <IPersistentConnection>();
            channel = Substitute.For <IModel>();
            var eventBus      = new EventBus();
            var configuration = new ConnectionConfiguration();

            var shutdownArgs = new ShutdownEventArgs(
                ShutdownInitiator.Peer,
                AmqpException.ConnectionClosed,
                "connection closed by peer");
            var exception = new OperationInterruptedException(shutdownArgs);

            persistentConnection.CreateModel().Returns(x => { throw exception; },
                                                       x => channel,
                                                       x => channel);


            var logger = Substitute.For <IEasyNetQLogger>();

            persistentChannel = new PersistentChannel(persistentConnection, logger, configuration, eventBus);

            new Timer(_ => eventBus.Publish(new ConnectionCreatedEvent()), null, 10, Timeout.Infinite);

            persistentChannel.InvokeChannelAction(x => x.ExchangeDeclare("MyExchange", "direct"));
        }
示例#6
0
        public StartConsumingStatus StartConsuming(IPersistentConnection connection, ICollection <Tuple <IQueue, Func <byte[], MessageProperties, MessageReceivedInfo, Task> > > queueConsumerPairs, IConsumerConfiguration configuration)
        {
            Preconditions.CheckNotNull(connection, nameof(connection));
            Preconditions.CheckNotNull(queueConsumerPairs, nameof(queueConsumerPairs));
            Preconditions.CheckNotNull(configuration, nameof(configuration));


            IDictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "x-priority", configuration.Priority },
                { "x-cancel-on-ha-failover", configuration.CancelOnHaFailover || connectionConfiguration.CancelOnHaFailover }
            };

            try
            {
                Model = connection.CreateModel();

                Model.BasicQos(0, configuration.PrefetchCount, true);


                basicConsumers = new List <BasicConsumer>();

                foreach (var p in queueConsumerPairs)
                {
                    var queue       = p.Item1;
                    var onMessage   = p.Item2;
                    var consumerTag = conventions.ConsumerTagConvention();
                    try
                    {
                        var basicConsumers = new BasicConsumer(SingleBasicConsumerCancelled, consumerDispatcher, queue, eventBus, handlerRunner, onMessage, logger, Model);

                        Model.BasicConsume(
                            queue.Name,  // queue
                            false,       // noAck
                            consumerTag, // consumerTag
                            true,
                            configuration.IsExclusive,
                            arguments,       // arguments
                            basicConsumers); // consumer
                        this.basicConsumers.Add(basicConsumers);

                        logger.InfoWrite("Declared Consumer. queue='{0}', consumer tag='{1}' prefetchcount={2} priority={3} x-cancel-on-ha-failover={4}",
                                         queue.Name, consumerTag, configuration.PrefetchCount, configuration.Priority, configuration.CancelOnHaFailover);
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorWrite("Consume failed. queue='{0}', consumer tag='{1}', message='{2}'",
                                          queue.Name, consumerTag, ex.Message);
                        return(StartConsumingStatus.Failed);
                    }
                }
            }
            catch (Exception exception)
            {
                logger.ErrorWrite("Consume failed. queue='{0}', message='{1}'",
                                  string.Join(";", queueConsumerPairs.Select(x => x.Item1.Name)), exception.Message);
                return(StartConsumingStatus.Failed);
            }
            return(StartConsumingStatus.Succeed);
        }
示例#7
0
        public void StartConsuming(
            IPersistentConnection connection,
            IQueue queue,
            Func <byte[], MessageProperties, MessageReceivedInfo, Task> onMessage)
        {
            Preconditions.CheckNotNull(connection, "connection");
            Preconditions.CheckNotNull(queue, "queue");
            Preconditions.CheckNotNull(onMessage, "onMessage");

            this.queue     = queue;
            this.onMessage = onMessage;
            var consumerTag = conventions.ConsumerTagConvention();

            try
            {
                Model = connection.CreateModel();

                Model.BasicQos(0, connectionConfiguration.PrefetchCount, false);

                Model.BasicConsume(
                    queue.Name,         // queue
                    false,              // noAck
                    consumerTag,        // consumerTag
                    this);              // consumer

                logger.InfoWrite("Declared Consumer. queue='{0}', consumer tag='{1}' prefetchcount={2}",
                                 queue.Name, consumerTag, connectionConfiguration.PrefetchCount);
            }
            catch (Exception exception)
            {
                logger.InfoWrite("Consume failed. queue='{0}', consumer tag='{1}', message='{2}'",
                                 queue.Name, consumerTag, exception.Message);
            }
        }
示例#8
0
 private void OpenChannel()
 {
     channel      = connection.CreateModel();
     disconnected = false;
     eventBus.Publish(new PublishChannelCreatedEvent(channel));
     logger.DebugWrite("Persistent channel connected.");
 }
示例#9
0
        private IModel CreateChannel()
        {
            var channel = connection.CreateModel();

            AttachChannelEvents(channel);
            return(channel);
        }
示例#10
0
        public IBasicGetResult Get(IQueue queue)
        {
            Preconditions.CheckNotNull(queue, "queue");

            //var result = clientCommandDispatcher.Invoke(x => x.BasicGet(queue.Name, false));
            RabbitMQ.Client.IModel model = connection.CreateModel();
            model.ContinuationTimeout = connectionConfiguration.ContinuationTimeout;
            var result = model.BasicGet(queue.Name, false);

            if (result == null)
            {
                return(null);
            }
            else
            {
                model.BasicAck(result.DeliveryTag, false);
            }

            var getResult = new BasicGetResult(
                result.Body,
                new MessageProperties(result.BasicProperties),
                new MessageReceivedInfo(
                    "",
                    result.DeliveryTag,
                    result.Redelivered,
                    result.Exchange,
                    result.RoutingKey,
                    queue.Name
                    )
                );

            logger.DebugWrite("Message Get from queue '{0}'", queue.Name);

            return(getResult);
        }
示例#11
0
        public StartConsumingStatus StartConsuming(
            IPersistentConnection connection,
            IQueue queue,
            Func <byte[], MessageProperties, MessageReceivedInfo, Task> onMessage,
            IConsumerConfiguration configuration
            )
        {
            Preconditions.CheckNotNull(connection, "connection");
            Preconditions.CheckNotNull(queue, "queue");
            Preconditions.CheckNotNull(onMessage, "onMessage");
            Preconditions.CheckNotNull(configuration, "configuration");

            var consumerTag = conventions.ConsumerTagConvention();
            IDictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "x-priority", configuration.Priority }
            };

            try
            {
                Model = connection.CreateModel();

                var basicConsumer = new BasicConsumer(SingleBasicConsumerCancelled, consumerDispatcher, queue, eventBus, handlerRunner, onMessage, Model);

                basicConsumers = new[] { basicConsumer };

                Model.BasicQos(0, configuration.PrefetchCount, false);

                Model.BasicConsume(
                    queue.Name,         // queue
                    false,              // noAck
                    consumerTag,        // consumerTag
                    true,
                    configuration.IsExclusive,
                    arguments,          // arguments
                    basicConsumer);     // consumer

                logger.InfoFormat(
                    "Declared consumer with consumerTag {consumerTag} on queue {queue} and configuration {configuration}",
                    consumerTag,
                    queue.Name,
                    configuration
                    );


                return(StartConsumingStatus.Succeed);
            }
            catch (Exception exception)
            {
                logger.Error(
                    exception,
                    "Consume with consumerTag {consumerTag} from queue {queue} has failed",
                    consumerTag,
                    queue.Name
                    );
                return(StartConsumingStatus.Failed);
            }
        }
示例#12
0
        public void Publish(IntegrationEvent @event)
        {
            if (!_connection.IsConnected)
            {
                if (!_connection.Connect())
                {
                    _logger.LogWarning($"Couldn't publish event {@event.Id}. No available connection was found.");
                    return;
                }
            }

            using (var ch = _connection.CreateModel())
            {
                DeclareExchange(ch);
                var msg = JsonSerializer.SerializeToUtf8Bytes(@event, @event.GetType());
                ch.BasicPublish(_exchangeName,
                                routingKey: _subscriptionManager.GetEventKey(@event.GetType()),
                                body: msg);
            }
        }
示例#13
0
        private void SubsManager_OnEventRemoved(object sender, string eventName)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            using (var channel = _persistentConnection.CreateModel())
            {
                channel.QueueUnbind(queue: _queueName,
                                    exchange: BROKER_NAME,
                                    routingKey: eventName);

                if (_subscriptionsManager.IsEmpty)
                {
                    _queueName = string.Empty;
                    _consumerChannel.Close();
                }
            }
        }
示例#14
0
        public virtual void Subscribe(IQueue queue, Func <Byte[], MessageProperties, MessageReceivedInfo, Task> onMessage)
        {
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }
            if (onMessage == null)
            {
                throw new ArgumentNullException("onMessage");
            }
            if (disposed)
            {
                throw new EasyNetQException("This bus has been disposed");
            }

            var subscriptionAction = new SubscriptionAction(queue.IsSingleUse);

            subscriptionAction.Action = () =>
            {
                var channel = connection.CreateModel();
                channel.ModelShutdown += (model, reason) => logger.DebugWrite("Model Shutdown for queue: '{0}'", queue.Name);

                queue.Visit(new TopologyBuilder(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));
                });

                channel.BasicConsume(
                    queue.Name,             // queue
                    NoAck,                  // noAck
                    consumer.ConsumerTag,   // consumerTag
                    consumer);              // consumer

                logger.DebugWrite("Declared Consumer. queue='{0}', prefetchcount={1}",
                                  queue.Name,
                                  connectionConfiguration.PrefetchCount);
            };

            AddSubscriptionAction(subscriptionAction);
        }
示例#15
0
        public StartConsumingStatus StartConsuming(
            IPersistentConnection connection,
            IQueue queue,
            Func <byte[], MessageProperties, MessageReceivedInfo, Task> onMessage,
            IConsumerConfiguration configuration
            )
        {
            Preconditions.CheckNotNull(connection, "connection");
            Preconditions.CheckNotNull(queue, "queue");
            Preconditions.CheckNotNull(onMessage, "onMessage");
            Preconditions.CheckNotNull(configuration, "configuration");

            var consumerTag = conventions.ConsumerTagConvention();
            IDictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "x-priority", configuration.Priority },
                { "x-cancel-on-ha-failover", configuration.CancelOnHaFailover || connectionConfiguration.CancelOnHaFailover }
            };

            try
            {
                Model = connection.CreateModel();

                var basicConsumers = new BasicConsumer(SingleBasicConsumerCancelled, consumerDispatcher, queue, eventBus, handlerRunner, onMessage, logger, Model);

                this.basicConsumers = new[] { new BasicConsumer(SingleBasicConsumerCancelled, consumerDispatcher, queue, eventBus, handlerRunner, onMessage, logger, Model) };

                Model.BasicQos(0, configuration.PrefetchCount, false);

                //// if configured, re-establish the consumer on a ConsumerCancelled event.
                //if (queue.IsConsumerRepairable)
                //    ConsumerCancelled += (sender, args) => ConsumerReConnect(sender, consumerTag, configuration.IsExclusive, arguments,queue);

                Model.BasicConsume(
                    queue.Name,         // queue
                    false,              // noAck
                    consumerTag,        // consumerTag
                    true,
                    configuration.IsExclusive,
                    arguments,          // arguments
                    basicConsumers);    // consumer

                logger.InfoWrite("Declared Consumer. queue='{0}', consumer tag='{1}' prefetchcount={2} priority={3} x-cancel-on-ha-failover={4}",
                                 queue.Name, consumerTag, configuration.PrefetchCount, configuration.Priority, configuration.CancelOnHaFailover);
            }
            catch (Exception exception)
            {
                logger.ErrorWrite("Consume failed. queue='{0}', consumer tag='{1}', message='{2}'",
                                  queue.Name, consumerTag, exception.Message);
                return(StartConsumingStatus.Failed);
            }
            return(StartConsumingStatus.Succeed);
        }
示例#16
0
        public void Publish(EventBase @event)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            var model = JsonConvert.SerializeObject(@event);

            using (var channel = _persistentConnection.CreateModel())
            {
                channel.ExchangeDeclare(_exchangeName, ExchangeType.Fanout);

                var body = Encoding.UTF8.GetBytes(model);
                channel.BasicPublish(_exchangeName,
                                     routingKey: @event.GetType().Name,
                                     basicProperties: null,
                                     body: body);
                _logger.LogDebug("[x] Sent {0}", model);
            }
        }
示例#17
0
 private void InitModel(ushort prefetchCount, bool globalQos)
 {
     if (Model == null)
     {
         lock (modelLock)
         {
             if (Model == null)
             {
                 Model = connection.CreateModel();
                 Model.BasicQos(0, prefetchCount, globalQos);
             }
         }
     }
 }
示例#18
0
        public When_a_channel_action_is_invoked()
        {
            persistentConnection = Substitute.For <IPersistentConnection>();
            channel = Substitute.For <IModel>();
            var configuration = new ConnectionConfiguration();

            eventBus = Substitute.For <IEventBus>();

            persistentConnection.CreateModel().Returns(channel);

            persistentChannel = new PersistentChannel(persistentConnection, configuration, eventBus);

            persistentChannel.InvokeChannelAction(x => x.ExchangeDeclare("MyExchange", "direct"));
        }
        public void Publish(IEvent @event)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            var policy = RetryPolicy.Handle <BrokerUnreachableException>()
                         .Or <SocketException>()
                         .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                _logger.LogWarning(ex.ToString());
            });

            using (var channel = _persistentConnection.CreateModel())
            {
                var eventName = @event.GetType().Name;

                channel.ExchangeDeclare(exchange: BROKER_NAME,
                                        type: "direct");

                var message = JsonConvert.SerializeObject(@event);
                var body    = Encoding.UTF8.GetBytes(message);

                policy.Execute(() =>
                {
                    var properties          = channel.CreateBasicProperties();
                    properties.DeliveryMode = 2; // persistent

                    channel.BasicPublish(exchange: BROKER_NAME,
                                         routingKey: eventName,
                                         mandatory: true,
                                         basicProperties: properties,
                                         body: body);
                });
            }
        }
示例#20
0
        public StartConsumingStatus StartConsuming(
            IPersistentConnection connection,
            IQueue queue,
            Func <byte[], MessageProperties, MessageReceivedInfo, Task> onMessage,
            IConsumerConfiguration configuration
            )
        {
            Preconditions.CheckNotNull(connection, "connection");
            Preconditions.CheckNotNull(queue, "queue");
            Preconditions.CheckNotNull(onMessage, "onMessage");
            Preconditions.CheckNotNull(configuration, "configuration");

            this.queue         = queue;
            this.onMessage     = onMessage;
            this.configuration = configuration;

            var consumerTag = conventions.ConsumerTagConvention();
            IDictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "x-priority", configuration.Priority },
                { "x-cancel-on-ha-failover", configuration.CancelOnHaFailover || connectionConfiguration.CancelOnHaFailover }
            };

            try
            {
                Model = connection.CreateModel();

                Model.BasicQos(0, configuration.PrefetchCount, false);

                Model.BasicConsume(
                    queue.Name,         // queue
                    false,              // noAck
                    consumerTag,        // consumerTag
                    true,
                    configuration.IsExclusive,
                    arguments,          // arguments
                    this);              // consumer

                logger.InfoWrite("Declared Consumer. queue='{0}', consumer tag='{1}' prefetchcount={2} priority={3} x-cancel-on-ha-failover={4}",
                                 queue.Name, consumerTag, configuration.PrefetchCount, configuration.Priority, configuration.CancelOnHaFailover);
            }
            catch (Exception exception)
            {
                logger.ErrorWrite("Consume failed. queue='{0}', consumer tag='{1}', message='{2}'",
                                  queue.Name, consumerTag, exception.Message);
                return(StartConsumingStatus.Failed);
            }
            return(StartConsumingStatus.Succeed);
        }
示例#21
0
        // ---------------------------------- Exchange / Queue / Binding -----------------------------------

        public IQueue QueueDeclare(
            string name,
            bool passive     = false,
            bool durable     = true,
            bool exclusive   = false,
            bool autoDelete  = false,
            uint perQueueTtl = UInt32.MaxValue,
            uint expires     = UInt32.MaxValue)
        {
            Preconditions.CheckNotNull(name, "name");

            using (var model = connection.CreateModel())
            {
                IDictionary <string, object> arguments = new Dictionary <string, object>();
                if (passive)
                {
                    model.QueueDeclarePassive(name);
                }
                else
                {
                    if (perQueueTtl != uint.MaxValue)
                    {
                        arguments.Add("x-message-ttl", perQueueTtl);
                    }

                    if (expires != uint.MaxValue)
                    {
                        arguments.Add("x-expires", expires);
                    }

                    model.QueueDeclare(name, durable, exclusive, autoDelete, (IDictionary)arguments);

                    logger.DebugWrite("Declared Queue: '{0}' durable:{1}, exclusive:{2}, autoDelte:{3}, args:{4}",
                                      name, durable, exclusive, autoDelete, WriteArguments(arguments));
                }

                return(new Topology.Queue(name, exclusive));
            }
        }
示例#22
0
        public StartConsumingStatus StartConsuming(
            IPersistentConnection connection,
            IQueue queue,
            Func<byte[], MessageProperties, MessageReceivedInfo, Task> onMessage,
            IConsumerConfiguration configuration
            )
        {
            Preconditions.CheckNotNull(connection, "connection");
            Preconditions.CheckNotNull(queue, "queue");
            Preconditions.CheckNotNull(onMessage, "onMessage");
            Preconditions.CheckNotNull(configuration, "configuration");

            this.queue = queue;
            this.onMessage = onMessage;
            var consumerTag = conventions.ConsumerTagConvention();
            IDictionary<string, object> arguments = new Dictionary<string, object>
                {
                    {"x-priority", configuration.Priority},
                    {"x-cancel-on-ha-failover", configuration.CancelOnHaFailover || connectionConfiguration.CancelOnHaFailover}
                };
            try
            {
                Model = connection.CreateModel();

                Model.BasicQos(0, configuration.PrefetchCount, false);

                Model.BasicConsume(
                    queue.Name,         // queue
                    false,              // noAck
                    consumerTag,        // consumerTag
                    true,
                    configuration.IsExclusive,
                    arguments,          // arguments
                    this);              // consumer

                logger.InfoWrite("Declared Consumer. queue='{0}', consumer tag='{1}' prefetchcount={2} priority={3} x-cancel-on-ha-failover={4}",
                                  queue.Name, consumerTag, configuration.PrefetchCount, configuration.Priority, configuration.CancelOnHaFailover);
            }
            catch (Exception exception)
            {
                logger.ErrorWrite("Consume failed. queue='{0}', consumer tag='{1}', message='{2}'",
                                 queue.Name, consumerTag, exception.Message);
                return StartConsumingStatus.Failed;
            }
            return StartConsumingStatus.Succeed;
        }
示例#23
0
        public void Publish(Event @event)
        {
            var eventName   = @event.GetType().Name;
            var jsonMessage = JsonConvert.SerializeObject(@event);
            var body        = Encoding.UTF8.GetBytes(jsonMessage);

            var message = new Message
            {
                MessageId = Guid.NewGuid().ToString(),
                Body      = body,
                Label     = eventName,
            };

            var topicClient = _persistentConnection.CreateModel();

            _logger.LogInformation($"Sending message to {topicClient.TopicName} topic");

            topicClient.SendAsync(message)
            .GetAwaiter()
            .GetResult();
        }
示例#24
0
        private IModel OpenChannel()
        {
            IModel channel;

            lock (this)
            {
                if (internalChannel != null)
                {
                    return(internalChannel);
                }

                channel = connection.CreateModel();

                WireUpChannelEvents(channel);

                eventBus.Publish(new PublishChannelCreatedEvent(channel));

                internalChannel = channel;
            }

            logger.Debug("Persistent channel connected");
            return(channel);
        }
示例#25
0
        private IModel CreateBasicChannel()
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            var channel = _persistentConnection.CreateModel();

            channel.ExchangeDeclare(
                Settings.ExchangeName,
                Settings.ExchangeType,
                true,
                false,
                Settings.WithDelay
                    ? new Dictionary <string, object>
            {
                { "x-delayed-type", "direct" }
            }
                    : null
                );

            return(channel);
        }
示例#26
0
        public void RawPublish(string exchangeName, string topic, string typeName, byte[] messageBody, byte priority)
        {
            if (!connection.IsConnected)
            {
                throw new EasyNetQException("Publish failed. No rabbit server connected.");
            }

            try
            {
                if (!threadLocalPublishChannel.IsValueCreated)
                {
                    threadLocalPublishChannel.Value = connection.CreateModel();
                    modelList.Add(threadLocalPublishChannel.Value);
                }
                DeclarePublishExchange(threadLocalPublishChannel.Value, exchangeName);

                var defaultProperties = threadLocalPublishChannel.Value.CreateBasicProperties();
                defaultProperties.SetPersistent(false);
                defaultProperties.Type          = typeName;
                defaultProperties.CorrelationId = getCorrelationId();
                defaultProperties.Priority      = priority;

                threadLocalPublishChannel.Value.BasicPublish(
                    exchangeName,      // exchange
                    topic,             // routingKey
                    defaultProperties, // basicProperties
                    messageBody);      // body

                logger.DebugWrite("Published {0}, CorrelationId {1}", exchangeName, 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);
            }
        }
示例#27
0
        public StartConsumingStatus StartConsuming(IPersistentConnection connection, ICollection <Tuple <IQueue, Func <byte[], MessageProperties, MessageReceivedInfo, Task> > > queueConsumerPairs, IConsumerConfiguration configuration)
        {
            Preconditions.CheckNotNull(connection, nameof(connection));
            Preconditions.CheckNotNull(queueConsumerPairs, nameof(queueConsumerPairs));
            Preconditions.CheckNotNull(configuration, nameof(configuration));


            IDictionary <string, object> arguments = new Dictionary <string, object>
            {
                { "x-priority", configuration.Priority }
            };

            try
            {
                Model = connection.CreateModel();

                Model.BasicQos(0, configuration.PrefetchCount, true);

                basicConsumers = new List <BasicConsumer>();

                foreach (var p in queueConsumerPairs)
                {
                    var queue       = p.Item1;
                    var onMessage   = p.Item2;
                    var consumerTag = conventions.ConsumerTagConvention();
                    try
                    {
                        var basicConsumer = new BasicConsumer(SingleBasicConsumerCancelled, consumerDispatcher, queue, eventBus, handlerRunner, onMessage, Model);

                        Model.BasicConsume(
                            queue.Name,  // queue
                            false,       // noAck
                            consumerTag, // consumerTag
                            true,
                            configuration.IsExclusive,
                            arguments,    // arguments
                            basicConsumer // consumer
                            );

                        basicConsumers.Add(basicConsumer);

                        logger.InfoFormat(
                            "Declared consumer with consumerTag {consumerTag} on queue={queue} and configuration {configuration}",
                            queue.Name,
                            consumerTag,
                            configuration
                            );
                    }
                    catch (Exception exception)
                    {
                        logger.Error(
                            exception,
                            "Consume with consumerTag {consumerTag} on queue {queue} failed",
                            queue.Name,
                            consumerTag
                            );
                        return(StartConsumingStatus.Failed);
                    }
                }

                return(StartConsumingStatus.Succeed);
            }
            catch (Exception exception)
            {
                logger.Error(
                    exception,
                    "Consume on queue {queue} failed",
                    string.Join(";", queueConsumerPairs.Select(x => x.Item1.Name))
                    );
                return(StartConsumingStatus.Failed);
            }
        }
示例#28
0
        public void StartConsuming(
            IPersistentConnection connection,
            IQueue queue,
            Func<byte[], MessageProperties, MessageReceivedInfo, Task> onMessage,
            IConsumerConfiguration configuration
            )
        {
            Preconditions.CheckNotNull(connection, "connection");
            Preconditions.CheckNotNull(queue, "queue");
            Preconditions.CheckNotNull(onMessage, "onMessage");
            Preconditions.CheckNotNull(configuration, "configuration");

            this.queue = queue;
            this.onMessage = onMessage;
            var consumerTag = conventions.ConsumerTagConvention();
            IDictionary<string, object> arguments = new Dictionary<string, object>
                {
                    {"x-priority", configuration.Priority}
                };
            try
            {
                Model = connection.CreateModel();

                Model.BasicQos(0, connectionConfiguration.PrefetchCount, false);

                Model.BasicConsume(
                    queue.Name,         // queue
                    false,              // noAck
                    consumerTag,        // consumerTag
                    arguments,          // arguments
                    this);              // consumer

                logger.InfoWrite("Declared Consumer. queue='{0}', consumer tag='{1}' prefetchcount={2} priority={3}",
                                  queue.Name, consumerTag, connectionConfiguration.PrefetchCount, configuration.Priority);
            }
            catch (Exception exception)
            {
                logger.InfoWrite("Consume failed. queue='{0}', consumer tag='{1}', message='{2}'",
                                 queue.Name, consumerTag, exception.Message);
            }
        }
        /// <inheritdoc />
        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 requeued",
                    context.ReceivedInfo
                    );

                return(AckStrategies.NackWithRequeue);
            }

            logger.Error(
                exception,
                "Exception thrown by subscription callback, receivedInfo={receivedInfo}, properties={properties}, message={message}",
                context.ReceivedInfo,
                context.Properties,
                Convert.ToBase64String(context.Body)
                );

            try
            {
                using var model = connection.CreateModel();
                if (configuration.PublisherConfirms)
                {
                    model.ConfirmSelect();
                }

                var errorExchange = DeclareErrorExchangeWithQueue(model, context);

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

                model.BasicPublish(errorExchange, context.ReceivedInfo.RoutingKey, properties, messageBody);

                if (!configuration.PublisherConfirms)
                {
                    return(AckStrategies.Ack);
                }

                return(model.WaitForConfirms(configuration.Timeout) ? AckStrategies.Ack : AckStrategies.NackWithRequeue);
            }
            catch (BrokerUnreachableException unreachableException)
            {
                // thrown if the broker is unreachable during 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.NackWithRequeue);
        }