public void Dispose()
 {
     _channel?.Dispose();
     _channel = null;
     _connection?.Dispose();
     _connection = null;
 }
Ejemplo n.º 2
0
        private IConnection CreateConnection(RabbitMQ.Client.IConnection connection,
                                             IModel outboundModel)
        {
            var builder = new ConsumedMessageBuilder(_configuration.SerializationConfiguration,
                                                     _configuration.MessageTypeResolver);
            var outboundChannel = _configuration.OutboundChannelBuilder(outboundModel,
                                                                        _configuration);
            var consumers = _promises.Select(_ =>
            {
                var model = CreateInboundModel(connection,
                                               _configuration.PrefetchSize,
                                               _configuration.PrefetchCount);
                var consumer = _(builder).BuildConsumer(new InboundChannel(model),
                                                        outboundChannel);
                return(new { Model = model, Consumer = consumer });
            })
                            .ToList();

            foreach (var consumer in consumers)
            {
                consumer.Consumer.Declare(consumer.Model);
            }

            return(new Connection(connection,
                                  consumers.Select(_ => _.Consumer),
                                  outboundChannel,
                                  _configuration));
        }
Ejemplo n.º 3
0
        public Task Close()
        {
            if (!taskQueue.IsValueCreated)
            {
                return(Task.CompletedTask);
            }

            return(taskQueue.Value.Add(() =>
            {
                if (channelInstance != null)
                {
                    channelInstance.Dispose();
                    channelInstance = null;
                }

                // ReSharper disable once InvertIf
                if (connection != null)
                {
                    connection.Dispose();
                    connection = null;
                }

                taskQueue.Value.Dispose();
            }));
        }
Ejemplo n.º 4
0
 /// <summary>
 /// 生产者
 /// </summary>
 /// <param name="settings"></param>
 /// <param name="delayedMessageEnabled">延迟消息已启用(需启用插件 rabbitmq_delayed_message_exchange)</param>
 /// <param name="autoConfig">自动建Exchange和Bind</param>
 public Producer(ProducerSettings settings, bool delayedMessageEnabled, bool autoConfig)
 {
     if (settings == null)
     {
         throw new ArgumentNullException(nameof(settings));
     }
     if (settings.AmqpConnection == null && settings.AmqpUri == null)
     {
         throw new ArgumentNullException("AmqpConnection or AmqpUri must be set.");
     }
     _clientName = string.IsNullOrEmpty(settings.ClientName) ? "undefined producer client" : settings.ClientName;
     _amqpUri    = settings.AmqpUri;
     if (settings.AmqpConnection != null)
     {
         _amqpConnection = settings.AmqpConnection;
         _clientName     = settings.AmqpConnection.ClientProvidedName;
     }
     if (settings.SendMsgTimeout > 0)
     {
         _sendMsgTimeout = TimeSpan.FromSeconds(settings.SendMsgTimeout);
     }
     if (settings.MaxChannelIdleDuration > 0)
     {
         _maxIdleDuration = TimeSpan.FromSeconds(settings.MaxChannelIdleDuration);
     }
     _delayedMessageEnabled = delayedMessageEnabled;
     _autoConfig            = autoConfig;
     _channelPool           = new ConcurrentQueue <Tuple <DateTime, IRabbitMQChannel> >();
     _cleanIdleChannelTimer = new Timer(ClearIdleChannel);
 }
Ejemplo n.º 5
0
        private static void WriteMessage(RabbitMQ.Client.IConnection conn, string from)
        {
            Console.Write("To: ");
            var to = Console.ReadLine();

            if (String.IsNullOrEmpty(to))
            {
                return;
            }

            Console.Write("Message: ");
            var message = Console.ReadLine();

            try
            {
                using (var model = conn.CreateModel())
                {
                    model.BasicReturn += new EventHandler <RabbitMQ.Client.Events.BasicReturnEventArgs>(blabla);

                    var rabbitMessage = new RabbitMessage()
                    {
                        From = from, Message = message
                    };
                    var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(rabbitMessage));
                    model.BasicPublish(to + "Exchange", string.Empty, new BasicProperties()
                    {
                        DeliveryMode = 2
                    }, body);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Registers the mq listen and hubs.
        /// </summary>
        public static void RegisterMQListenAndHubs()
        {
            ConnectionFactory factory = new ConnectionFactory();

            factory.UserName = "******";
            // "gue
            factory.Password    = "******";
            factory.VirtualHost = "/";
            factory.HostName    = "192.168.1.105";
            RabbitMQ.Client.IConnection conn = factory.CreateConnection();
            IModel channel  = conn.CreateModel();
            var    consumer = new EventingBasicConsumer(channel);

            consumer.Received += (ch, ea) =>
            {
                var body = ea.Body;

                if (body != null)
                {
                    string message = System.Text.Encoding.Default.GetString(body);

                    GlobalHost.ConnectionManager.GetHubContext <RealTimeDataHub>().Clients.All.realData(message);
                }

                ((IModel)ch).BasicAck(ea.DeliveryTag, false);
            };

            String consumerTag = channel.BasicConsume("lenovo", false, consumer);
        }
        /// <summary>
        /// 执行关闭
        /// </summary>
        /// <returns>事件数据</returns>
        protected override object ExecClose()
        {
            if (channels.Count > 0)
            {
                foreach (IModel channel in channels)
                {
                    if (channel.IsOpen)
                    {
                        channel.Close();
                        channel.Dispose();
                    }
                }

                channels.Clear();
            }

            if (Status == ConnectionStatusType.OPENED)
            {
                connection.Close();
                connection.Dispose();
            }

            connection  = null;
            virtualPath = RabbitConnectionInfo.DEFAULT_VIRTUAL_PATH;

            return(null);
        }
Ejemplo n.º 8
0
        public void Dispose()
        {
            lock (this.syncRoot)
            {
                try
                {
                    this.Close();

                    if (this.connection != null)
                    {
                        this.logger.Trace(
                            $"[{this.endpoint}]: disposing connection [{this.Id}] at [{this.connection.Endpoint}].");
                        this.connection?.Dispose();
                        this.connection = null;
                    }
                }
                catch (Exception ex)
                {
                    this.logger.Trace($"An error '{ex.Message}' during connection cleanup has been suppressed");
                }
                finally
                {
                    this.OnDisposed();
                }
            }
        }
Ejemplo n.º 9
0
        public void Open(CancellationToken token)
        {
            this.logger.Info($"Connecting to RabbitMQ using [{this.ConnectionString}].");

            var clientProperties = new Dictionary <string, object>
            {
                {
                    "Endpoint",
                    this.endpoint.Address
                },
                { "Machine", Environment.MachineName },
                {
                    "Location",
                    Path.GetDirectoryName(
                        Assembly.GetExecutingAssembly().CodeBase)
                }
            };

            var connectionFactory = new ConnectionFactory
            {
                Uri = this.ConnectionString,
                ClientProperties           = clientProperties,
                RequestedConnectionTimeout = ConnectionTimeout
            };

            var retryCount = 0;

            while (!token.IsCancellationRequested)
            {
                INativeConnection con = null;
                try
                {
                    con = connectionFactory.CreateConnection();
                    con.ConnectionShutdown += this.OnConnectionShutdown;
                    this.connection         = con;
                    this.OnOpened();
                    this.logger.Info($"Connection [{this.Id}] opened at [{this.connection.Endpoint}]");

                    return;
                }
                catch (Exception ex)
                {
                    var secondsToRetry = Math.Min(10, retryCount);

                    this.logger.WarnFormat(
                        "Unable to connect to RabbitMQ. Retrying in {0} seconds...",
                        ex,
                        secondsToRetry);

                    if (con != null)
                    {
                        con.ConnectionShutdown -= this.OnConnectionShutdown;
                        con.Abort(OperationTimeout);
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(secondsToRetry));
                    retryCount++;
                }
            }
        }
Ejemplo n.º 10
0
        } // AmqpClient

        #region ConnectionHandlerProgram

        private Exception MakeNewConnection(ref RmqCl.IConnection connection, ref RmqCl.IModel channel, bool reconnecting)
        {
            // This method attempts to make a new connection. Returns true if success, otherwise false.

            var connRequest = ConnectionRequestObj;

            var factory = new RmqCl.ConnectionFactory()
            {
                HostName = connRequest.Host,
                UserName = connRequest.Username,
                Password = connRequest.Password
            };

            // Secure connection?
            if (connRequest.Secure)
            {
                factory.Ssl.Enabled    = true;
                factory.Ssl.ServerName = connRequest.Host;
                factory.Ssl.Version    = System.Security.Authentication.SslProtocols.Tls12;
            }

            try
            {
                // Create connection and channel
                connection = factory.CreateConnection();
                channel    = connection.CreateModel();

                // Declare the exchange
                channel.ExchangeDeclare(exchange: connRequest.Exchange, type: "topic", autoDelete: false, durable: true, arguments: null);

                // Create a queue to receive messages
                var queueName = channel.QueueDeclare(queue: "",        // Use a generated queue name
                                                     durable: false,   // The queue does not survive a broker restart
                                                     exclusive: true,  // The queue is only for this application, and it will be deleted on app exit
                                                     autoDelete: true, // The queue is deleted when no one is bound to it
                                                     arguments: null
                                                     ).QueueName;

                // Bind the queue to the topic pattern
                channel.QueueBind(queue: queueName, exchange: connRequest.Exchange, routingKey: connRequest.TopicPattern, arguments: null);

                // Set up a consumer for messages
                m_messageConsumer           = new RmqCl.Events.EventingBasicConsumer(channel);
                m_messageConsumer.Received += MessageReceived;
                channel.BasicConsume(queue: queueName, noAck: true, consumerTag: "", noLocal: false, exclusive: false, arguments: new Dictionary <string, object> {
                }, consumer: m_messageConsumer);

                // Sign up for the shutdown event
                channel.ModelShutdown += ModelShutdown; // This event will fire if the connection is lost

                return(null);
            }
            catch (Exception e)
            {
                // Clean the connection
                DestroyConnection(ref connection, ref channel);

                return(e);
            }
        } // MakeNewConnection
        /// <summary>
        /// 关闭
        /// </summary>
        public override void Close()
        {
            if (channels.Count > 0)
            {
                foreach (IModel channel in channels)
                {
                    if (channel.IsOpen)
                    {
                        channel.Close();
                        channel.Dispose();
                    }
                }

                channels.Clear();
            }

            if (Status == ConnectionStatusType.OPENED)
            {
                connection.Close();
                connection.Dispose();
            }

            connection = null;

            OnClosed();
        }
 public void Dispose()
 {
     if (!(_connection is null))
     {
         _connection.Dispose();
         _connection = null;
     }
 }
Ejemplo n.º 13
0
        protected internal virtual IModel CreateInboundModel(RabbitMQ.Client.IConnection connection,
                                                             UInt32 prefetchSize,
                                                             UInt16 prefetchCount)
        {
            var model = connection.CreateModel();

            model.BasicQos(prefetchSize, prefetchCount, false);
            return(model);
        }
Ejemplo n.º 14
0
 private void OnConnectionShutdown(INativeConnection conn, ShutdownEventArgs eventArgs)
 {
     Task.Factory.StartNew(
         () =>
     {
         conn.ConnectionShutdown -= this.OnConnectionShutdown;
         this.OnClosed();
     });
 }
Ejemplo n.º 15
0
        //options
        internal IModel CreateChannel(IConnection connection)
        {
            var channel = connection.CreateModel();

            channel.QueueDeclare(QueueName, Durable, Exclusive, AutoDelete, Arguments);

            //configure channel using options here
            return(channel);
        }
Ejemplo n.º 16
0
        private void ConnectionHandlerProgram()
        {
            // This method is run in the connection handler thread.
            // Multiple variables are declared here, because this limits their access for this thread only.

            RmqCl.IConnection connection = null;
            RmqCl.IModel      channel    = null;

            // This indicates if the connection is being restored
            bool connectionRestoreSequenceOn = false;

            // Run the thread until "break"
            while (true)
            {
                // Wait for something to happen.
                // This wait has a maximum length, as this same wait call occurs between reconnect attempts.
                m_connectionWait.WaitOne(TimeSpan.FromSeconds(RetryIntervalSeconds));

                // Choosing what to do based on the flags
                if (m_disposed.Value || m_userHasRequestedTerminate.Value)
                {
                    // Quitting
                    break;
                }
                else if (m_triggerConnectionRestore.Value || connectionRestoreSequenceOn)
                {
                    // Connection lost! Attempting to restore.

                    // Reset the triggering flag
                    m_triggerConnectionRestore.Value = false;

                    // Keep on attempting restore until successful
                    connectionRestoreSequenceOn = !AttemptConnectionRestore(ref connection, ref channel);
                }
                else if (ConnectionRequestObj != null && connection == null)
                {
                    // Attempting to connect

                    SendConnectionEvent(true, ConnectionEventType.Connecting);
                    var exception = MakeNewConnection(ref connection, ref channel, false);

                    if (exception == null)
                    {
                        SendConnectionEvent(true, ConnectionEventType.Connected);
                    }
                    else
                    {
                        SendConnectionEvent(false, ConnectionEventType.ConnectingFailed, exception);
                    }
                }
                // Otherwise, nothing to do
            }

            // Quitting the thread
            TerminateImpl(ref connection, ref channel);
            m_connectionWait.Dispose();
        } // ConnectionHandlerProgram
Ejemplo n.º 17
0
        public static void CreateConnection()
        {
            _factory = new ConnectionFactory {
                HostName = "localhost", UserName = "******", Password = "******"
            };
            _connection = _factory.CreateConnection();

            _model = _connection.CreateModel();
            _model.ExchangeDeclare(ExchangeName, "fanout", true);
        }
        public RabbitMQConnection(string exchange, Rabbit.IConnection connection)
        {
            if (string.IsNullOrWhiteSpace(exchange))
            {
                throw new ArgumentNullException(nameof(exchange));
            }

            _exchange   = exchange;
            _connection = connection ?? throw new ArgumentNullException(nameof(connection));
        }
Ejemplo n.º 19
0
        /// <remarks>
        /// Only call this from a task in the taskQueue to ensure IModel is only used
        /// by a single thread, as is recommended in the RabbitMQ .NET Client documentation.
        /// </remarks>
        private async Task <IModel> GetChannel(int?maxAttempts = null)
        {
            if (channelInstance != null)
            {
                return(channelInstance);
            }

            var attempts          = 0;
            var connectionFactory = new ConnectionFactory
            {
                HostName    = ConnectionParams.HostName,
                Port        = ConnectionParams.Port,
                VirtualHost = ConnectionParams.VirtualHost,
                UserName    = ConnectionParams.Username,
                Password    = ConnectionParams.Password,
                AutomaticRecoveryEnabled = true, // The created connection is an IRecoverable
                RequestedHeartbeat       = 30
            };

            while (true)
            {
                try
                {
                    connection      = connectionFactory.CreateConnection();
                    channelInstance = connection.CreateModel();

                    if (ConnectionParams.PrefetchCount > 0)
                    {
                        channelInstance.BasicQos(0, ConnectionParams.PrefetchCount, false);
                    }

                    ((IRecoverable)connection).Recovery += (sender, e) => ConnectionEventListener?.Reconnected();

                    channelInstance.ModelShutdown += (sender, e) => ConnectionEventListener?.Disconnected();

                    ConnectionEventListener?.Connected();
                    break;
                }
                catch (BrokerUnreachableException)
                {
                    attempts++;
                    if (maxAttempts.HasValue && attempts > maxAttempts.Value)
                    {
                        throw;
                    }

                    await Task.Delay(ReconnectDelay);
                }
            }

            return(channelInstance);
        }
Ejemplo n.º 20
0
        public RabbitMQWrapper(RabbitMQ.Client.IConnection connection)
        {
            _rmqConnection = connection;
            _rmqModel      = _rmqConnection.CreateModel();

            _rmqModel.ExchangeDeclare(_exchangeName, ExchangeType.Topic);

            _serializerSettings = new JsonSerializerSettings
            {
                ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore
            };
        }
Ejemplo n.º 21
0
        private void SetupConnection()
        {
            if (_connection != null && _connection.IsOpen)
            {
                return;
            }

            _connection?.Dispose();

            _connection = _factory.CreateConnection();
            _connection.ConnectionShutdown += _connection_ConnectionShutdown;
            _logger.LogInformation("Connection is ready");
        }
Ejemplo n.º 22
0
        public void Constructor_NullConnection_ArgumentNullException()
        {
            //Arrange
            string exchange = nameof(exchange);

            Rabbit.IConnection connection = null;

            //Act
            var action = new Action(() => new RabbitMQConnection(exchange, connection));

            //Assert
            Assert.Throws <ArgumentNullException>(nameof(connection), action);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 关闭
        /// </summary>
        public void Shutdown()
        {
            if (Interlocked.CompareExchange(ref _isRunning, 0, 1) == 1)
            {
                Thread.Sleep(100);
                if (_amqpConnection != null)
                {
                    if (_mode == ConsumeMode.Push)
                    {
                        foreach (var topic in _globalConsumers.Keys)
                        {
                            var consumers = _globalConsumers[topic];
                            foreach (var queueIndex in consumers.Keys)
                            {
                                var channel = consumers[queueIndex].Model;
                                if (channel.IsOpen)
                                {
                                    channel.Close(RabbitMQConstants.ConnectionForced, $"\"{topic}-{queueIndex}\"'s normal channel disposed");
                                }
                            }
                            consumers.Clear();
                        }
                        _globalConsumers.Clear();
                    }
                    else
                    {
                        foreach (var topic in _globalChannels.Keys)
                        {
                            var channels = _globalChannels[topic];
                            foreach (var queueIndex in channels.Keys)
                            {
                                var channel        = channels[queueIndex].Item1;
                                var consumerThread = channels[queueIndex].Item2;
                                if (channel.IsOpen)
                                {
                                    channel.Close(RabbitMQConstants.ConnectionForced, $"\"{topic}-{queueIndex}\"'s normal channel disposed");
                                }
                            }
                            channels.Clear();
                        }
                        _globalChannels.Clear();
                    }

                    if (_selfCreate)
                    {
                        _amqpConnection.Close();
                        _amqpConnection = null;
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public void Open(CancellationToken token)
        {
            lock (this.syncRoot)
            {
                if (this.connection?.IsOpen ?? false)
                {
                    this.logger.Trace($"Connection [{this.Id}] is already open");
                    return;
                }

                this.logger.Info($"Connecting to RabbitMQ using [{this.ConnectionString}]");

                var retryCount = 0;
                while (true)
                {
                    token.ThrowIfCancellationRequested();

                    INativeConnection con = null;
                    try
                    {
                        con = this.connectionFactory.CreateConnection();
                        con.ConnectionShutdown += this.OnConnectionShutdown;
                        this.connection         = con;
                        this.OnOpened();
                        this.logger.Info($"Connection [{this.Id}] opened at [{this.connection.Endpoint}]");

                        return;
                    }
                    catch (Exception ex)
                    {
                        var secondsToRetry = Math.Min(10, retryCount);

                        this.logger.WarnFormat(
                            "Unable to connect to RabbitMQ. Retrying in {0} seconds...",
                            ex,
                            secondsToRetry);

                        if (con != null)
                        {
                            con.ConnectionShutdown -= this.OnConnectionShutdown;
                            con.Abort(OperationTimeout);
                        }

                        Thread.Sleep(TimeSpan.FromSeconds(secondsToRetry));
                        retryCount++;
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private static RabbitMQ.Client.IConnection InitRabbitMqConn()
        {
            RabbitMqConfigs rabbitmqConfigs = new RabbitMqConfigs(_configs.GetSection("rabbitMq"));

            ConnectionFactory factory = new ConnectionFactory
            {
                HostName = rabbitmqConfigs.Host,
                Port     = rabbitmqConfigs.Port,
                UserName = rabbitmqConfigs.User,
                Password = rabbitmqConfigs.Password,
            };

            RabbitMQ.Client.IConnection rabbitmqConn = factory.CreateConnection();
            return(rabbitmqConn);
        }
Ejemplo n.º 26
0
        private void OnConnectionShutdown(INativeConnection conn, ShutdownEventArgs eventArgs)
        {
            Task.Factory.StartNew(
                () =>
            {
                this.logger.Trace($"Connection [{this.Id}] has been closed due to {eventArgs.ReplyText} ({eventArgs.ReplyCode})");

                lock (this.syncRoot)
                {
                    conn.ConnectionShutdown -= this.OnConnectionShutdown;
                }

                this.OnClosed();
            });
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            if (Interlocked.CompareExchange(ref _isRunning, 1, 0) == 0)
            {
                if (_amqpConnection == null)
                {
                    var connFactory = new RabbitMQConnectionFactory
                    {
                        Uri = _amqpUri
                    };
                    _amqpConnection = connFactory.CreateConnection(_clientName);
                    _selfCreate     = true;
                }

                if (_autoConfig)
                {
                    using (var channelForConfig = _amqpConnection.CreateModel())
                    {
                        foreach (var topic in _topics.Keys)
                        {
                            var queueCount      = _topics[topic];
                            var subscribeQueues = GetSubscribeQueues(queueCount, _consumerCount, _consumerSequence);
                            var subTopic        = GetSubTopic(topic);
                            channelForConfig.ExchangeDeclare(topic, ExchangeType.Fanout, true, false, null);
                            channelForConfig.ExchangeDeclare(subTopic, ExchangeType.Direct, true, false, null);
                            channelForConfig.ExchangeBind(subTopic, topic, "", null);

                            for (byte queueIndex = 0; queueIndex < queueCount; queueIndex++)
                            {
                                string queueName = GetQueue(topic, queueIndex);
                                channelForConfig.QueueDeclare(queueName, true, false, false, null);
                                channelForConfig.QueueBind(queueName, subTopic, queueIndex.ToString(), null);
                            }
                        }
                        channelForConfig.Close();
                    }
                }

                if (_mode == ConsumeMode.Push)
                {
                    ConsumeByPush();
                }
                else
                {
                    ConsumeByPull();
                }
            }
        }
 public RabbitMessageProcessor(
     ITransformer <TSrc, TDst> transformer,
     IWriter <TDst> writer,
     ILoggerFactory loggerFactory,
     IOptions <RabbitConfig> options,
     IConnection connection)
 {
     _writer       = writer;
     _connection   = connection;
     _logger       = loggerFactory.CreateLogger(GetType());
     _rabbitConfig = options.Value;
     _transformer  = transformer;
     _channel      = connection.CreateModel();
     _consumer     = new EventingBasicConsumer(_channel);
     _consumerTag  = Guid.NewGuid().ToString();
 }
Ejemplo n.º 29
0
 /// <summary>
 /// 每次重启时,清空队列
 /// </summary>
 public static void DeleteQueue()
 {
     using (IConnection conn = RabbitMqFactory.CreateConnection())
     {
         using (IModel channel = conn.CreateModel())
         {
             try
             {
                 channel.QueueDelete(QueueName, true, false);
             }
             catch (Exception e)
             {
                 LogWrite.WriteLogInfo($"重启时,存在消费者,不删除队列,异常{e.Message}");
             }
         }
     }
 }
Ejemplo n.º 30
0
 public EventConsumer()
 {
     _factory = new ConnectionFactory
     {
         HostName = HostName,
         UserName = UserName,
         Password = Password
     };
     _connection = _factory.CreateConnection();
     _model      = _connection.CreateModel();
     _model.QueueDeclare(QueueName, true, false, false, null);
     _model.QueueBind(QueueName, ExchangeName, "");
     _model.BasicQos(0, 1, false);
     _subscription   = new Subscription(_model, QueueName, false);
     _gameRepository = new MongoRepository <HSGame>();
     _deckRepository = new MongoRepository <HSDeck>();
 }
Ejemplo n.º 31
0
        public RabbitMqMessageBus(IDependencyResolver resolver, RabbitMqScaleoutConfiguration configuration)
            : base(resolver, configuration)
        {
            Open(0);
            
            var connectionFactory = CreateConnectionFactory(configuration);

            connection = connectionFactory.CreateConnection();

            model = connection.CreateModel();

            var exchange = configuration.ExchangeName ?? "messages";

            model.QueueDeclare(configuration.QueueName, false, false, true, new Hashtable());
            model.ExchangeDeclare(exchange, ExchangeType.Fanout);
            model.QueueBind(configuration.QueueName, exchange, "");

            consumerTag = model.BasicConsume(configuration.QueueName, true, new Consumer(this.OnReceived));
        }
Ejemplo n.º 32
0
 /// <summary>Initializes a new instance of the <see cref="SimpleConnection"/> class.</summary>
 /// <param name="connectionDelegate">The connection delegate.</param>
 public SimpleConnection(RabbitMQ.Client.IConnection connectionDelegate) { this.connectionDelegate = connectionDelegate; }
Ejemplo n.º 33
0
        protected virtual void ConnectToBroker()
        {
            if (_outboundModel != null && !_outboundModel.IsClosed) return;
            _connection = _connectionBuilder.CreateConnection(_configuration.EndpointUri);
            //Logger.DebugFormat("RMQMessagingGateway: Opening channel to Rabbit MQ on connection {0}", Configuration.AMPQUri.GetSanitizedUri());
            _outboundModel = _connection.CreateModel();
            //When AutoClose is true, the last channel to close will also cause the connection to close1. If it is set to
            //true before any channel is created, the connection will close then and there.
            if (_connection.AutoClose == false)
                _connection.AutoClose = true;

            foreach (var exchange in _exchanges)
                exchange.Declare(_outboundModel);

            foreach (var queue in _queues)
                queue.Declare(_outboundModel);

            foreach (var binding in _bindings)
                binding.Declare(_outboundModel);

            var builder = new ConsumedMessageBuilder(_configuration.SerializationConfiguration, _configuration.MessageTypeResolver);
            _outboundChannel = _configuration.OutboundChannelBuilder(_outboundModel, _configuration);
            var consumers = _promises.Select(_ =>
            {
                var model = CreateInboundModel(_connection, _configuration.PrefetchSize, _configuration.PrefetchCount);
                var consumer = _(builder).BuildConsumer(new InboundChannel(model), _outboundChannel);
                return new {Model = model, Consumer = consumer};
            })
                .ToList();

            foreach (var consumer in consumers)
                consumer.Consumer.Declare(consumer.Model);
            _consumers = consumers.Select(_ => _.Consumer);
        }
        /// <summary>
        /// Queues the exists.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="queue">The queue.</param>
        /// <returns></returns>
        /// Use native Rabbit API to test queue, bypassing all the connection and channel caching and callbacks in Spring
        /// AMQP.
        /// @param connection the raw connection to use
        /// @param queue the Queue to test
        /// @return true if the queue exists
        /// <remarks></remarks>
        private bool QueueExists(IConnection connection, Queue queue)
        {
            var target = connection;
            if (target == null)
            {
                var connectionFactory = new ConnectionFactory();
                connectionFactory.Port = BrokerTestUtils.GetPort();
                target = connectionFactory.CreateConnection();
            }

            var channel = target.CreateModel();
            try
            {
                var result = channel.QueueDeclarePassive(queue.Name);
                return result != null;
            }
            catch (Exception e)
            {
                if (e.Message.Contains("RESOURCE_LOCKED"))
                {
                    return true;
                }

                return false;
            }
            finally
            {
                if (connection == null)
                {
                    target.Close();
                }
            }
        }