Beispiel #1
0
        public void Handle <T>(T message)
        {
            var handlers = handlerFactory.GetHandlerFor <T>();

            foreach (var handler in handlers)
            {
                handler.Handle(message);

                handlerFactory.Release(handler);
            }
        }
        public void Run(MessageConfiguration config)
        {
            Bind(config.Handler.FullName, config.RoutingKey, connectionConfiguration.Exchange);

            Channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

            var consumer = new EventingBasicConsumer(Channel);

            consumer.Received += (sender, e) =>
            {
                try
                {
                    var message = Encoding.UTF8.GetString(e.Body);
                    messageLogger.Info($" [x] Received '{e.RoutingKey}':'{message}'");

                    var handler = handlerFactory.Resolve(config.Handler.FullName);
                    handler.Handle(message);
                    handlerFactory.Release(handler);

                    Channel.BasicAck(deliveryTag: e.DeliveryTag, multiple: false);
                }
                catch (Exception exception)
                {
                    Channel.BasicReject(deliveryTag: e.DeliveryTag, requeue: false);

                    if (e.BasicProperties.Headers == null)
                    {
                        e.BasicProperties.Headers = new Dictionary <string, object>();
                    }
                    e.BasicProperties.Headers.Add("Queue", config.Handler.FullName);

                    Channel.BasicPublish(exchange: connectionConfiguration.PoisionExchange,
                                         routingKey: config.RoutingKey,
                                         basicProperties: e.BasicProperties,
                                         body: e.Body);

                    messageLogger.Error(exception);
                    throw;
                }
            };

            Channel.BasicConsume(queue: config.Handler.FullName,
                                 autoAck: false,
                                 consumer: consumer);
        }