コード例 #1
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
コード例 #2
0
        private SimpleConsumer Consume(string queue, Connection.IConnection connection)
        {
            R.IModel       channel  = null;
            SimpleConsumer consumer = null;

            try
            {
                channel = connection.CreateChannel(IsChannelTransacted);
                channel.BasicQos(0, (ushort)PrefetchCount, false);  // TODO: Verify this
                consumer = new SimpleConsumer(this, connection, channel, queue);
                channel.QueueDeclarePassive(queue);
                consumer.ConsumerTag = channel.BasicConsume(
                    queue,
                    AcknowledgeMode.IsAutoAck(),
                    ConsumerTagStrategy != null ? ConsumerTagStrategy.CreateConsumerTag(queue) : string.Empty,
                    NoLocal,
                    Exclusive,
                    ConsumerArguments,
                    consumer);
            }

            // catch (AmqpApplicationContextClosedException e)
            // {
            //    throw new AmqpConnectException(e);
            // }
            catch (Exception e)
            {
                RabbitUtils.CloseChannel(channel, _logger);
                RabbitUtils.CloseConnection(connection, _logger);

                consumer = HandleConsumeException(queue, consumer, e);
            }

            return(consumer);
        }
コード例 #3
0
        public void Start()
        {
            _consumer.Received += ProcessMessage;

            _channel.BasicConsume(
                queue: _rabbitConfig.Queue,
                autoAck: false,
                exclusive: false,
                consumerTag: _consumerTag,
                consumer: _consumer);
        }
コード例 #4
0
        public void ReviceMessage(string queueName, string someone, Action <string> eventHandel)
        {
            EventingBasicConsumer consumer = new EventingBasicConsumer(_chanel);

            _chanel.ExchangeDeclare(exchangeName, exchangeType, false, false, null);
            //_chanel.ExchangeDeclare(exchangeName, exchangeType);
            _chanel.QueueDeclare(queueName, false, false, false, null);//持久化  排他性 自动删除
            _chanel.QueueBind(queueName, exchangeName, routingKey, null);
            //_chanel.QueueBind(queueName, exchangeName, routingKey + someone);//交换机与
            consumer.Received += (ch, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body);
                eventHandel?.Invoke(message);
                _chanel.BasicAck(ea.DeliveryTag, false);//确认该消息已被消费
            };
            _chanel.BasicConsume(queueName, false, consumer);
            //_chanel.BasicConsume(queueName, false, consumer); //启动消费者

            // Console.WriteLine("客户端2已启动");
        }
コード例 #5
0
        private void StartBasicConsume()
        {
            _logger.LogTrace("Starting RabbitMQ basic consume");

            if (_consumerChannel != null)
            {
                var consumer = new AsyncEventingBasicConsumer(_consumerChannel);

                consumer.Received += Consumer_Received;

                _consumerChannel.BasicConsume(
                    queue: _queueName,
                    autoAck: false,
                    consumer: consumer);
            }
            else
            {
                _logger.LogError("StartBasicConsume can't call on _consumerChannel == null");
            }
        }
コード例 #6
0
        private async Task Run(string[] args)
        {
            var host  = ConfigurationManager.AppSettings["rabbit.host"];
            var user  = ConfigurationManager.AppSettings["rabbit.admuser"];
            var pwd   = ConfigurationManager.AppSettings["rabbit.admpwd"];
            var vhost = ConfigurationManager.AppSettings["rabbit.vhost"];

            LogAdapter.LogDebugFn              = (s, s1, arg3) => { };
            LogAdapter.ExtendedLogEnabled      = false;
            LogAdapter.ProtocolLevelLogEnabled = false;

            _hdrHistogram = new LongHistogram(1, 1000 * 10, 5);

            int  howManyQueues        = 10;
            bool exclusiveConnections = ConfigurationManager.AppSettings["exclusiveConnections"] == "true";
            bool useOfficialClient    = ConfigurationManager.AppSettings["useOfficialClient"] == "true";

            if (useOfficialClient)
            {
                RabbitMQ.Client.IConnection conn    = null;
                RabbitMQ.Client.IModel      channel = null;

                for (int i = 0; i < howManyQueues; i++)
                {
                    var connFac = new RabbitMQ.Client.ConnectionFactory()
                    {
                        HostName = host, UserName = user, Password = pwd, VirtualHost = vhost, AutomaticRecoveryEnabled = false
                    };

                    if (exclusiveConnections || conn == null)
                    {
                        conn    = connFac.CreateConnection();
                        channel = conn.CreateModel();
                        channel.BasicQos(0, 300, false);
                    }

                    var q = "q." + i;
                    channel.QueueDeclareNoWait(q, durable: true, exclusive: false, autoDelete: false, arguments: null);

                    channel.BasicConsume(q, false, "con_" + q, arguments: null, consumer: new Consumer(channel));
                }
            }
            else
            {
                RabbitMqNext.IConnection conn    = null;
                RabbitMqNext.IChannel    channel = null;

                for (int i = 0; i < howManyQueues; i++)
                {
                    if (exclusiveConnections || conn == null)
                    {
                        conn = await RabbitMqNext.ConnectionFactory.Connect(host, vhost, user, pwd, recoverySettings : null, connectionName : "mod_perf_server");

                        channel = await conn.CreateChannel();

                        await channel.BasicQos(0, 300, false);
                    }

                    var q = "q." + i;

                    await channel.QueueDeclare(q, passive : false, durable : true, exclusive : false, autoDelete : false, arguments : null,
                                               waitConfirmation : false);

                    // TODO: test with parallel buffer copy + serialized too
                    await channel.BasicConsume(ConsumeMode.SerializedWithBufferCopy, BuildConsumerFn(channel), q, "consumer_" + q,
                                               false, true, arguments : null, waitConfirmation : false);
                }
            }

            Console.WriteLine("Consuming..");

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Done\r\n");
                Console.WriteLine("howManyQueues {0} exclusive Connections: {1} official client: {2} count {3}", howManyQueues, exclusiveConnections, useOfficialClient, _hdrHistogram.TotalCount);
                Console.WriteLine("\r\n");

                _hdrHistogram.OutputPercentileDistribution(Console.Out);

                Console.ReadKey();
            };

            await Task.Delay(1);

            Thread.CurrentThread.Join();
        }