public void TestQueueDeclareOk()
        {
            Model.ConfirmSelect();
            QueueDeclareOk result;

            result = QueueDeclare();
            Assert.AreEqual(0, result.MessageCount);
            Assert.AreEqual(0, result.ConsumerCount);
            Assert.AreEqual(QueueName, result.QueueName);
            Model.BasicPublish("", result.QueueName, null, new byte[] { });
            Model.WaitForConfirms();

            result = QueueDeclare();
            Assert.AreEqual(1, result.MessageCount);
            Assert.AreEqual(0, result.ConsumerCount);
            Assert.AreEqual(QueueName, result.QueueName);

            QueueingBasicConsumer consumer = new QueueingBasicConsumer(Model);
            Model.BasicConsume(QueueName, true, consumer);
            consumer.Queue.Dequeue();

            result = QueueDeclare();
            Assert.AreEqual(0, result.MessageCount);
            Assert.AreEqual(1, result.ConsumerCount);
            Assert.AreEqual(QueueName, result.QueueName);
        }
예제 #2
0
        private void ConsumeInTheBackGround()
        {
            Task.Factory.StartNew(() => {
                var connectionFactory = new ConnectionFactory
                {
                    HostName = "rabbitmq.cloudvirga.local",
                    Port     = Protocols.DefaultProtocol.DefaultPort,
                    UserName = "******",
                    Password = "******"
                };

                var connection = connectionFactory.CreateConnection();
                var model      = connection.CreateModel();
                var consumer   = new QueueingBasicConsumer(model);
                model.BasicConsume("Ayman.Queue", false, consumer);
                while (true)
                {
                    var deliveryArgs = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    var message = Encoding.Default.GetString(deliveryArgs.Body);
                    Invoke(new MethodInvoker(() =>
                    {
                        listBox1.Items.Insert(0, message);
                    }
                                             ));

                    model.BasicAck(deliveryArgs.DeliveryTag, false);
                }
            });
        }
예제 #3
0
        static void Main(string[] args)
        {
            Console.Title        = "Consumer1";
            Console.WindowHeight = 7;
            Console.WindowWidth  = 50;

            string exchange = "eip.selcons.pub";
            string queue    = "eip.selcons.queue01";

            var factory = new ConnectionFactory()
            {
                Uri = "amqp://*****:*****@localhost:5672/"
            };

            using (var conn = factory.CreateConnection())
                using (IModel channel = conn.CreateModel())
                {
                    channel.ExchangeDeclare(exchange, ExchangeType.Direct, true);
                    channel.QueueDeclare(queue, true, false, false, null);
                    channel.QueueBind(queue, exchange, "consumer1");

                    QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);

                    channel.BasicConsume(queue, true, consumer);

                    while (true)
                    {
                        var ea      = consumer.Queue.Dequeue();
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(message);
                    }
                }
        }
예제 #4
0
        /// <summary>
        /// 消费消息
        /// </summary>
        /// <param name="connection">消息队列连接对象</param>
        /// <param name="queueName">队列名称</param>
        /// <param name="durable">是否持久化</param>
        /// <param name="dealMessage">消息处理函数</param>
        /// <param name="saveLog">保存日志方法,可选</param>
        public static void ConsumeMsg(IConnection connection, string queueName, bool durable, Func <string, ConsumeAction> dealMessage, Action <string, Exception> saveLog = null)
        {
            try
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queueName, durable, false, false, null); //获取队列
                    channel.BasicQos(0, 1, false);                                //分发机制为触发式

                    var consumer = new QueueingBasicConsumer(channel);            //建立消费者
                    // 从左到右参数意思分别是:队列名称、是否读取消息后直接删除消息,消费者
                    channel.BasicConsume(queueName, false, consumer);

                    while (true)  //如果队列中有消息
                    {
                        ConsumeAction consumeResult = ConsumeAction.RETRY;
                        var           ea            = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); //获取消息
                        string        message       = null;
                        try
                        {
                            var body = ea.Body;
                            message       = Encoding.UTF8.GetString(body);
                            consumeResult = dealMessage(message);
                        }
                        catch (Exception ex)
                        {
                            if (saveLog != null)
                            {
                                saveLog(message, ex);
                            }
                        }
                        if (consumeResult == ConsumeAction.ACCEPT)
                        {
                            channel.BasicAck(ea.DeliveryTag, false);  //消息从队列中删除
                        }
                        else if (consumeResult == ConsumeAction.RETRY)
                        {
                            channel.BasicNack(ea.DeliveryTag, false, true); //消息重回队列
                        }
                        else
                        {
                            channel.BasicNack(ea.DeliveryTag, false, false); //消息直接丢弃
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (saveLog != null)
                {
                    saveLog("QueueName:" + queueName, ex);
                }
                throw ex;
            }
            finally
            {
                ResetMQConnectionToFree(connection);
            }
        }
예제 #5
0
 public Listener(string exchangeName, string hostName, int portNumber, string queueName)
     : base(exchangeName, hostName, portNumber)
 {
     channel.QueueDeclare(queueName);
     consumer = new QueueingBasicConsumer(channel);
     channel.BasicConsume(queueName, null, consumer);
     this.queueName = queueName;
 }
예제 #6
0
        public QueueingBasicConsumer ReceiveMessage(string queueName = "")
        {
            //EventingBasicConsumer
            var consumer = new QueueingBasicConsumer(channel);

            channel.BasicConsume(queueName, true, consumer);
            return(consumer);
        }
예제 #7
0
 private void HandleConsumerCancelled(object sender, ConsumerEventArgs e)
 {
     lock (m_eventLock)
     {
         m_consumer = null;
         MutateLatestEvent(null);
     }
 }
예제 #8
0
        private static BasicDeliverEventArgs DequeueMessage(QueueingBasicConsumer consumer)
        {
            const int timeoutMilseconds = 400;
            object    result;

            consumer.Queue.Dequeue(timeoutMilseconds, out result);
            return(result as BasicDeliverEventArgs);
        }
예제 #9
0
 public Listener(string exchangeName, string queueName, IConnection conn)
     : base(exchangeName, conn)
 {
     channel.QueueDeclare(queueName);
     consumer = new QueueingBasicConsumer(channel);
     channel.BasicConsume(queueName, null, consumer);
     this.queueName = queueName;
 }
예제 #10
0
    //public string m_terminal_id;

    public void DoWork()
    {
        IModel channel = m_connection.CreateModel();

        //string rpc_queue = "rpc_queue_" + m_routingkey_root; // terminal_id
        string rpc_queue = "rpc_queue";

        channel.QueueDeclare(rpc_queue, false, false, false, null);
        channel.BasicQos(0, 1, false);
        var consumer = new QueueingBasicConsumer(channel);

        channel.BasicConsume(rpc_queue, false, consumer);
        MessageBox.Show(" [x] Awaiting RPC requests on '" + rpc_queue + "'");

        _shouldStop = false;

        while (!_shouldStop)
        {
            MessageBox.Show("worker thread: working...");


            /*
             * MessageBox.Show("wait message");
             *
             * string response = null;
             * var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
             *
             * var body = ea.Body;
             * var props = ea.BasicProperties;
             * var replyProps = channel.CreateBasicProperties();
             * replyProps.CorrelationId = props.CorrelationId;
             *
             * try
             * {
             *  var message = Encoding.UTF8.GetString(body);
             *  MessageBox.Show(message);
             *  //m_message = message.ToString();
             *  //int n = int.Parse(message);
             *  //Console.WriteLine(" [.] fib({0})", message);
             *  //response = fib(n).ToString();
             * }
             * catch (Exception e)
             * {
             *  MessageBox.Show(" [.] Exception");
             *  //MessageBox.Show(" [.] " + e.Message);
             *  response = "";
             * }
             * finally
             * {
             *  MessageBox.Show("finally");
             *  //var responseBytes = Encoding.UTF8.GetBytes(response);
             *  //channel.BasicPublish("", props.ReplyTo, replyProps, responseBytes);
             *  //channel.BasicAck(ea.DeliveryTag, false);
             * }
             */
        }
        MessageBox.Show("worker thread: terminating gracefully.");
    }
예제 #11
0
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost", UserName = "******", Password = "******"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare("MY_EXCHANGE_NAME", "topic", true);
                    var queueName = channel.QueueDeclare("TV Queue", true, false, false, null);


                    if (args.Length < 1)
                    {
                        Console.Error.WriteLine("Usage: {0} [binding_key...]",
                                                Environment.GetCommandLineArgs()[0]);
                        Environment.ExitCode = 1;
                        return;
                    }

                    foreach (var bindingKey in args)
                    {
                        channel.QueueBind(queueName, "MY_EXCHANGE_NAME", bindingKey);
                    }

                    Console.WriteLine(" [*] Waiting for messages. " +
                                      "To exit press CTRL+C");

                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, true, consumer);

                    while (true)
                    {
                        var ea         = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                        var routingKey = ea.RoutingKey;
                        var body       = ea.Body;

                        MemoryStream stream = new MemoryStream(body, false);

                        stream.Position = 0;

                        var message = Serializer.Deserialize <Listing>(stream);


                        Console.WriteLine(" [x] Received '{0}':'{1}'",
                                          routingKey, message.ToString());

                        Console.WriteLine("Program Name: {0}", message.ProgramName);
                        Console.WriteLine("Episode Name: {0}", message.EpisodeName);
                        Console.WriteLine("Episode Number: {0}", message.EpisodeNumber);
                        Console.WriteLine("Is Live: {0}", message.IsLive);
                    }
                }
            }
        }
예제 #12
0
        public IActionResult Chat(ChatModel model)
        {
            var outModel = new ChatModel();

            // Check if we have the ChatEntries queue initialized
            var chatEntriesQueue = HttpContext.Session.Get <Queue <ChatEntry> >("ChatEntriesQueue");

            if (chatEntriesQueue == null)
            {
                // Initialize the queue
                chatEntriesQueue = new Queue <ChatEntry>();
            }

            if (ModelState.IsValid)
            {
                // Add the entry to the queue
                var newChat = new ChatEntry {
                    DatePosted = DateTime.UtcNow, Text = model.ChatText, WhoPosted = User.Identity.Name
                };
                _model.BasicPublish(ExchangeName, "chat", null, newChat.Serialize());
            }

            // Connect to our rabbit queue and retrieve messages
            _model.BasicQos(prefetchSize: 0, prefetchCount: 10, global: false);
            var queueName = $"Chat_{User.Identity.Name}_Queue";
            var _consumer = new QueueingBasicConsumer(_model);

            _model.BasicConsume(queue: queueName, autoAck: false, _consumer);
            while (true)
            {
                if (!_consumer.Queue.Dequeue(millisecondsTimeout: 100, out var result))
                {
                    break;
                }
                var message = (ChatEntry)result.Body.DeSerialize(typeof(ChatEntry));
                // Check for stock commands
                if (!message.Text.StartsWith("/stock=", StringComparison.InvariantCultureIgnoreCase))
                {
                    chatEntriesQueue.Enqueue(new ChatEntry {
                        DatePosted = message.DatePosted, Text = message.Text, WhoPosted = message.WhoPosted
                    });
                }
                // Acknowledge
                _model.BasicAck(result.DeliveryTag, false);
            }

            // Take the last 50 entries of the local queue
            outModel.ChatEntries = chatEntriesQueue.TakeLast(50).ToList();
            // Remove old ones
            while (chatEntriesQueue.Count > 50)
            {
                chatEntriesQueue.Dequeue();
            }
            // Add the local queue back to the session
            HttpContext.Session.Set <Queue <ChatEntry> >("ChatEntriesQueue", chatEntriesQueue);

            return(View(outModel));
        }
예제 #13
0
    public static void Main()
    {
        var factory = new ConnectionFactory()
        {
            HostName = "localhost"
        };

        using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "rpc_queue",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);
                channel.BasicQos(0, 1, false);
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(queue: "rpc_queue",
                                     noAck: false,
                                     consumer: consumer);
                Console.WriteLine(" [x] Awaiting RPC requests");

                while (true)
                {
                    string response = null;
                    var    ea       = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    var body       = ea.Body;
                    var props      = ea.BasicProperties;
                    var replyProps = channel.CreateBasicProperties();
                    replyProps.CorrelationId = props.CorrelationId;

                    try
                    {
                        var message = Encoding.UTF8.GetString(body);
                        int n       = int.Parse(message);
                        Console.WriteLine(" [.] fib({0})", message);
                        response = fib(n).ToString();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(" [.] " + e.Message);
                        response = "";
                    }
                    finally
                    {
                        var responseBytes = Encoding.UTF8.GetBytes(response);
                        channel.BasicPublish(exchange: "",
                                             routingKey: props.ReplyTo,
                                             basicProperties: replyProps,
                                             body: responseBytes);
                        channel.BasicAck(deliveryTag: ea.DeliveryTag,
                                         multiple: false);
                    }
                }
            }
    }
예제 #14
0
        public ReceiverWaitingSubscription(IModel model, string queueName)
        {
            mModel     = model;
            mQueueName = queueName;
            mConsumer  = new QueueingBasicConsumer(model);
            model.BasicConsume(queueName, false, mConsumer);

            mSubscription = new Subscription(mModel, mQueueName);
        }
예제 #15
0
            public Consumer(string queueName, IConnection connection, Func <byte[], Option <T> > dataConverter)
            {
                this.dataConverter = dataConverter;
                model = connection.CreateModel();
                model.BasicQos(0, (ushort)Environment.ProcessorCount, false);

                consumer = new QueueingBasicConsumer(model);
                model.BasicConsume(queueName, false, consumer);
            }
예제 #16
0
        public static void ConsumeMessagesStart(string agentId)
        {
            consumer = new QueueingBasicConsumer(channel);

            // turn auto acknowledge off so we can do it manually. This is so we don't remove items from the queue until we're perfectly happy
            const bool autoAck = false;

            channel.BasicConsume(ConnectionConstants.AgentQueueName + "-" + agentId, autoAck, consumer);
        }
예제 #17
0
 ///<summary>Creates a new Subscription, with full control over
 ///both "noAck" mode, the name of the queue, and the consumer tag.</summary>
 public Subscription(IModel model, string queueName, bool noAck, string consumerTag)
 {
     Model       = model;
     QueueName   = queueName;
     NoAck       = noAck;
     m_consumer  = new QueueingBasicConsumer(Model);
     ConsumerTag = Model.BasicConsume(QueueName, NoAck, consumerTag, m_consumer);
     LatestEvent = null;
 }
예제 #18
0
        protected void Start(AMQPAdapter amqpAdapter, bool catchAllExceptions)
        {
            base.Start(amqpAdapter);
            try {
                var connection = (IConnection)amqpAdapter.GetConnection();

                using (var channel = connection.CreateModel()) {
                    if (createQueue)
                    {
                        channel.QueueDeclare(queueName, true, false, false, queueArgs);
                    }
                    channel.BasicQos(0, prefetchCount, false);

                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, noAck, consumer);

                    while (!stopConsuming)
                    {
                        try {
                            BasicDeliverEventArgs basicDeliverEventArgs;
                            var messageIsAvailable = consumer.Queue.Dequeue(timeout, out basicDeliverEventArgs);

                            if (!messageIsAvailable)
                            {
                                continue;
                            }
                            var payload = basicDeliverEventArgs.Body;

                            var message = Encoding.UTF8.GetString(payload);
                            OnMessageReceived(new MessageReceivedEventArgs {
                                Message   = message,
                                EventArgs = basicDeliverEventArgs
                            });

                            if (implicitAck && !noAck)
                            {
                                channel.BasicAck(basicDeliverEventArgs.DeliveryTag, false);
                            }
                        }
                        catch (Exception exception) {
                            OnMessageReceived(new MessageReceivedEventArgs {
                                Exception = new AMQPConsumerProcessingException(exception)
                            });
                            if (!catchAllExceptions)
                            {
                                Stop();
                            }
                        }
                    }
                }
            }
            catch (Exception exception) {
                OnMessageReceived(new MessageReceivedEventArgs {
                    Exception = new AMQPConsumerInitialisationException(exception)
                });
            }
        }
예제 #19
0
        private IEsbMessageResult DoSendQuery(IEsbMessage query)
        {
            _channel.QueueDeclare(queue: query.QueueName,
                                  durable: true,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);

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

            var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(query.MessageBody));

            var properties = _channel.CreateBasicProperties();

            properties.Persistent    = true;
            properties.ReplyTo       = Guid.NewGuid().ToString("N");
            properties.CorrelationId = Guid.NewGuid().ToString("N");

            _channel.BasicPublish(
                exchange: "",
                routingKey: query.QueueName,
                basicProperties: properties,
                body: body);

            _channel.QueueDeclare(properties.ReplyTo, false, true, true, null);
            var consumer = new QueueingBasicConsumer(_channel);

            try
            {
                _channel.BasicConsume(
                    queue: properties.ReplyTo,
                    noAck: true,
                    consumer: consumer);

                var startReceiveTime = DateTime.Now;
                while (true)
                {
                    BasicDeliverEventArgs res;
                    var answerReciwed = consumer.Queue.Dequeue(100, out res);
                    if (answerReciwed && res.BasicProperties.CorrelationId == properties.CorrelationId)
                    {
                        var answer = Encoding.UTF8.GetString(res.Body);
                        return(new EsbMessageResult(answer));
                    }

                    if (DateTime.Now - startReceiveTime > query.ReceiveTimeout)
                    {
                        throw new EsbMessageReceiveTimeoutException();
                    }
                }
            }
            finally
            {
                _channel.QueueDelete(properties.ReplyTo);
                consumer.Queue.Close();
            }
        }
예제 #20
0
        private static void Recv()
        {
            // 获取到连接以及mq通道
            ConnectionFactory factory = new ConnectionFactory();

            factory.Port        = 5672;                                                  //服务器端口号:默认端口号为:5672
            factory.Endpoint    = new AmqpTcpEndpoint(new Uri("amqp://172.21.26.120/")); //服务器IP:172.21.26.120;
            factory.UserName    = "******";                                               //服务器登录账号
            factory.Password    = "******";                                                //服务器密码账号
            factory.VirtualHost = "testhost";                                            //
            //factory.RequestedHeartbeat = heartbeat;
            using (IConnection conn = factory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    string Queue_Name = "q_test_01";
                    //声明消息队列
                    channel.QueueDeclare(Queue_Name, false, false, false, null);
                    // 同一时刻服务器只会发一条消息给消费者
                    channel.BasicQos(0, 1, false);     //BasicQos(1);
                                                       // 定义队列的消费者
                    var consumer = new QueueingBasicConsumer(channel);
                    //监听队列,false表示手动返回完成状态,true表示自动
                    channel.BasicConsume(Queue_Name, false, consumer);

                    #region 获取消息
                    while (true)
                    {
                        ulong deliveryTag = 0;
                        try
                        {
                            Thread.Sleep(1000);//暂停1秒,防止CPU爆满的问题

                            //获取信息
                            var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                            deliveryTag = ea.DeliveryTag;
                            byte[] bytes = ea.Body;
                            string str   = Encoding.UTF8.GetString(bytes);

                            logger.Info($"获取到服务器队列{Queue_Name}的信息:{str}");
                            //回复确认处理成功
                            channel.BasicAck(deliveryTag, false);
                            //发生错误了,但是还可以重新提交给队列重新分配
                            //channel.BasicNack(deliveryTag, false, true);
                            //发生严重错误,无法继续进行,这种情况应该写日志或者是发送消息通知管理员
                            //channel.BasicNack(deliveryTag, false, false);
                        }
                        catch (Exception ex)
                        {
                            //channel.BasicNack(deliveryTag, false, false);
                            //logger.Info($"获取到服务器队列{Queue_Name}的信息失败:{ex.Message}");
                        }
                    }
                    #endregion
                }
            }
        }
예제 #21
0
        public DefaultBasicConsumer CreateConsumer(IModel model, MessageCallback callback)
        {
            var consumer    = new QueueingBasicConsumer(model, sharedQueue);
            var consumerTag = Guid.NewGuid().ToString();

            consumer.ConsumerTag = consumerTag;
            subscriptions.Add(consumerTag, new SubscriptionInfo(consumer, callback));
            return(consumer);
        }
 ///<summary>Creates a new Subscription, with full control over
 ///both "noAck" mode, the name of the queue, and the consumer tag.</summary>
 public Subscription(IModel model, string queueName, bool noAck, string consumerTag)
 {
     m_model       = model;
     m_queueName   = queueName;
     m_noAck       = noAck;
     m_consumer    = new QueueingBasicConsumer(m_model);
     m_consumerTag = m_model.BasicConsume(m_queueName, m_noAck, consumerTag, m_consumer);
     m_latestEvent = null;
 }
예제 #23
0
        private static string DeclareAndBindQueueToExchange(IModel channel)
        {
            channel.ExchangeDeclare(ExchangeName, "fanout");
            var queueName = channel.QueueDeclare().QueueName;

            channel.QueueBind(queueName, ExchangeName, "");
            _consumer = new QueueingBasicConsumer(channel);
            return(queueName);
        }
예제 #24
0
        /// <summary>
        /// 订阅模式接收消息
        /// </summary>
        /// <param name="handler">接收到消息后的处理</param>
        public override void ReceivingMessagesPassive(MessageHandler handler)
        {
            var cf = new ConnectionFactory
            {
                Uri                = ServerAddress,
                UserName           = UserName,
                Password           = Password,
                VirtualHost        = VirtualHost,
                RequestedHeartbeat = 0
            };

            using (var conn = cf.CreateConnection())
            {
                using (var ch = conn.CreateModel())
                {
                    var consumer = new QueueingBasicConsumer(ch);
                    var i        = 1;

                    //noAck = true,不需要回复,接收到消息后,queue上的消息就会清除
                    //noAck = false,需要回复,接收到消息后,queue上的消息不会被清除,
                    //直到调用channel.basicAck(deliveryTag, false);
                    //queue上的消息才会被清除 而且,在当前连接断开以前,其它客户端将不能收到此queue上的消息
                    ch.BasicConsume(Queue, false /*noAck*/, consumer);
                    while (true)
                    {
                        try
                        {
                            var res = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                            if (res.Body.Length != 0)
                            {
                                Console.Write(i++ + "   ");
                                if (handler != null)
                                {
                                    handler(Deserialize(res.Body));
                                }

                                ch.BasicAck(res.DeliveryTag, false);
                            }
                            else
                            {
                                ch.BasicAck(res.DeliveryTag, false);
                                continue;
                            }

                            Console.WriteLine();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                            throw;
                        }
                    }
                }
            }
        }
예제 #25
0
        static void Receive()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //定义队列(hello为队列名)
                    channel.QueueDeclare(queueName, true, false, false, null);

                    ushort prefetechCount = 1;
                    channel.BasicQos(0, prefetechCount, false);

                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, true, consumer);

                    Console.WriteLine(" [*] Waiting for messages." +
                                      "To exit press CTRL+C");

                    var sw = new Stopwatch();
                    sw.Start();

                    while (true)
                    {
                        //接受客户端发送的消息并打印出来
                        //var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                        BasicDeliverEventArgs ea = null;
                        consumer.Queue.Dequeue(2000, out ea);

                        if (ea == null)
                        {
                            sw.Stop();

                            TimeSpan ts          = sw.Elapsed;
                            string   elapsedTime = String.Format("{0:00}:时 {1:00}:分 {2:00}:秒:{3:00}:毫秒",
                                                                 ts.Hours, ts.Minutes, ts.Seconds,
                                                                 ts.Milliseconds / 10);

                            Console.WriteLine(" [x] Consumer Complete.Total Time:{0}", elapsedTime);
                            Console.ReadLine();
                        }

                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        //Console.WriteLine(" [x] Received {0}", message);

                        //Thread.Sleep(5000);
                    }
                }
            }
        }
예제 #26
0
        static void Main(string[] args)
        {
            IConnection conn         = null;
            IModel      channel      = null;
            string      exchangeName = "exchange.oa";
            string      queueName    = "queue.oa.contactlist.apply";
            string      routingKey   = "generateno";

            try
            {
                ConnectionFactory connFactory = new ConnectionFactory()
                {
                    HostName = "10.7.249.21", VirtualHost = "/", UserName = "******", Password = "******"
                };
                conn    = connFactory.CreateConnection();
                channel = conn.CreateModel();
                channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, true, false, null);
                channel.QueueDeclare(queueName, true, false, false, null);
                channel.QueueBind(queueName, exchangeName, routingKey);
                channel.BasicQos(0, 1, false);//在一个工作者还在处理消息,并且没有响应消息之前,不要给他分发新的消息。相反,将这条新的消息发送给下一个不那么忙碌的工作者。
                var consumer = new QueueingBasicConsumer(channel);
                //将消费者与信道,队列相关联
                channel.BasicConsume(queue: queueName,
                                     noAck: false,//true:开启消息自动确认功能,false:关闭消息自动确认功能==>消息确认后会自动将消息从队列中删除
                                     consumer: consumer);
                while (true)
                {
                    try
                    {
                        var ea             = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                        var body           = ea.Body;
                        var messageContent = Encoding.UTF8.GetString(body);
                        channel.BasicAck(ea.DeliveryTag, false);
                        Console.WriteLine(messageContent);
                    }
                    catch (Exception innerex)
                    {
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (channel != null && channel.IsOpen)
                {
                    channel.Close();
                }
                if (conn != null && conn.IsOpen)
                {
                    conn.Close();
                }
            }
        }
예제 #27
0
        private void Run(string[] args)
        {
            // This application must monitor multiple queues and figure out
            // how to move the production work item forward based on which
            // queue sends a response.
            //
            // Here are the queues it needs to montior:
            // - The incoming request queue for newly submitted jobs
            // - The Worker1 response queue
            // - The Worker2 response queue

            QueueingBasicConsumer consumer = ConnectToMQ();

            LoadUncompletedJobs();

            while (true)
            {
                m_log.Info("Waiting for queue message...");

                BasicDeliverEventArgs ea;

                try
                {
                    if (consumer.Queue.Dequeue((int)TimeSpan.FromMilliseconds(500d).TotalMilliseconds, out ea))
                    {
                        // Process the message
                        //
                        // NOTE: It is the responsibility of these functions
                        // to send reply-to messages
                        switch (ea.RoutingKey)
                        {
                        case RabbitMQConfig.MCP_REQUEST_QUEUE_NAME:
                            ProcessMCPRequestQueueMessage(m_channel, ea);
                            break;

                        case RabbitMQConfig.WORKER1_RESPONSE_QUEUE_NAME:
                            ProcessWorker1ResponseQueueMessage(m_channel, ea);
                            break;

                        case RabbitMQConfig.WORKER2_RESPONSE_QUEUE_NAME:
                            ProcessWorker2ResponseQueueMessage(m_channel, ea);
                            break;
                        }
                    }

                    CleanupOldJobs();
                    LogStatus();
                }

                catch (EndOfStreamException eosEx)
                {
                    m_log.Warn("Connection to the queue was lost.");
                    consumer = ConnectToMQ();
                }
            }
        }
예제 #28
0
        void RecvThread()
        {
            try
            {
                conn.Open();
            }
            catch (MySqlException ex)
            {
            }
            var factory = new ConnectionFactory();

            factory.HostName = "localhost";
            factory.UserName = "******";
            factory.Password = "******";
            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    // When reading from a persistent queue, you need to tell that to your consumer
                    const bool durable = true;
                    channel.QueueDeclare(QueueName, durable, false, false, null);

                    var consumer = new QueueingBasicConsumer(channel);

                    // turn auto acknowledge off so we can do it manually. This is so we don't remove items from the queue until we're perfectly happy
                    const bool autoAck = false;
                    channel.BasicConsume(QueueName, autoAck, consumer);

                    string query2;
                    while (true)
                    {
                        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                        byte[] body    = ea.Body;
                        string message = System.Text.Encoding.UTF8.GetString(body);
                        System.Console.WriteLine(" [x] Processing {0}", message);

                        // Acknowledge message received and processed
                        System.Console.WriteLine(" Processed ", message);

                        channel.BasicAck(ea.DeliveryTag, false);

                        msg1 = message;

/*
 *                  if (message.Length > 10)
 *                  {
 *                      query2 = message;
 *                      MySqlCommand cmdSpkSel4 = conn.CreateCommand();
 *                      cmdSpkSel4.CommandText = query2;
 *                      cmdSpkSel4.ExecuteNonQuery();
 *                  }
 * */
                    }
                    conn.Close();
                }
        }
예제 #29
0
        private void fun()
        {
            var factory = new ConnectionFactory();

            factory.HostName = "localhost";
            factory.UserName = "******";
            factory.Password = "******";
            ProjectInfo buildProjectInfo = new ProjectInfo();

            while (true)
            {
                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare("CIQueues_newframework", false, false, false, null);

                        var consumer = new QueueingBasicConsumer(channel);
                        channel.BasicConsume("CIQueues_newframework", false, consumer);

                        var      ea                   = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                        var      body                 = ea.Body;
                        var      message              = Encoding.UTF8.GetString(body);
                        string[] messageSplit         = message.Split(';');
                        string   projectName          = messageSplit[0].Split(':')[1];
                        string   projectCommitVersion = messageSplit[1].Split(':')[1];
                        string   projectSubmitter     = messageSplit[2].Split(':')[1];
                        string   projectPushBranch    = messageSplit[3].Split(':')[1].Split('/')[2];
                        //对项目进行编译
                        buildProjectInfo = HandleProject(projectName, projectCommitVersion, projectPushBranch, projectSubmitter);
                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                }

                //对象转化为json格式的数据
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(buildProjectInfo.GetType());
                MemoryStream stream = new MemoryStream();
                serializer.WriteObject(stream, buildProjectInfo);
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                var factory_push = new ConnectionFactory();
                factory_push.HostName = "localhost";
                factory_push.UserName = "******";
                factory_push.Password = "******";
                using (var connection = factory_push.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare("BuildResultInfo", false, false, false, null);
                        var body = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(dataBytes));
                        channel.BasicPublish("", "BuildResultInfo", null, body);
                    }
                }
            }
        }
 public static void CreateQueue()
 {
     _factory = new ConnectionFactory {
         HostName = "localhost", UserName = "******", Password = "******"
     };
     _connection = _factory.CreateConnection();
     _model      = _connection.CreateModel();
     _model.QueueDeclare(QueueName, true, false, false, null);
     _consumer = new QueueingBasicConsumer(_model);
 }
예제 #31
0
        public void Unbind(RabbitMqConnection connection)
        {
            lock (_lock)
            {
                _consumer = null;

                _channel.Cleanup(200, "Unbind Consumer");
                _channel = null;
            }
        }
        public void ListenOnce()
        {
            if (this.channel == null)
             {
            this.channel = this.channelManager.CreateChannel();
            this.channel.BasicQos(0, 1, false);
             }

             if (this.consumer == null)
             {
            this.consumer = new QueueingBasicConsumer(this.channel);

            var messageTypes = this.messageHandlerTypesIndex.GetAllMessageTypes();

            foreach (var messageType in messageTypes)
            {
               var queueName = this.queueNameConvention.GetQueueName(messageType);

               this.channel.QueueDeclare(queueName, true, false, false, null);
               this.channel.BasicConsume(queueName, false, this.consumer);
            }
             }

             BasicDeliverEventArgs deliveryEvent;

             if (!this.consumer.Queue.Dequeue(this.configuration.ListenTimeout, out deliveryEvent))
             {
            return;
             }

             object message = null;

             try
             {
            var serialisedMessage = this.messageEncoder.Decode(deliveryEvent.Body);
            var messageType = this.queueNameConvention.GetMessageType(deliveryEvent.RoutingKey);
            message = this.messageSerialiser.Deserialise(serialisedMessage, messageType);
             }
             catch (Exception exception)
             {
            this.logger.LogError("An unexpected exception occured when decoding message:", exception);
             }

             if (message == null || !this.messageHandlerInvoker.Handle(message))
             {
            // TODO: Write to error queue
             }

             this.channel.BasicAck(deliveryEvent.DeliveryTag, false);
        }
        public void TestRecoverAfterCancel_()
        {
            UTF8Encoding enc = new UTF8Encoding();
            Channel.BasicPublish("", Queue, null, enc.GetBytes("message"));
            QueueingBasicConsumer Consumer = new QueueingBasicConsumer(Channel);

            String CTag = Channel.BasicConsume(Queue, false, Consumer);
            BasicDeliverEventArgs Event = (BasicDeliverEventArgs) Consumer.Queue.Dequeue();
            Channel.BasicCancel(CTag);
            Channel.BasicRecover(true);

            QueueingBasicConsumer Consumer2 = new QueueingBasicConsumer(Channel);
            Channel.BasicConsume(Queue, false, Consumer2);
            BasicDeliverEventArgs Event2 = (BasicDeliverEventArgs)Consumer2.Queue.Dequeue();

            Assert.AreEqual(Event.Body, Event2.Body);
            Assert.IsFalse(Event.Redelivered);
            Assert.IsTrue(Event2.Redelivered);
        }
예제 #34
0
        public static void ReturnMessageToSourceQueue(string errorQueueMachine, string errorQueueName, string userName, string password, string messageId)
        {
            using (IModel errorQueue = OpenQueue(errorQueueMachine, userName, password))
            {
                Dictionary<string, object> query = new Dictionary<string, object>
                {
                    {"message_id", messageId}
                };
                QueueingBasicConsumer consumer = new QueueingBasicConsumer(errorQueue);
                string basicConsume = errorQueue.BasicConsume(errorQueueName, false, Environment.UserName, false, true, query, consumer);

                BasicDeliverEventArgs deliverArgs = consumer.Queue.Dequeue();

                string failedQueueName;
                string failedMachineName;
                ReadFailedQueueHeader(out failedQueueName, deliverArgs, out failedMachineName);

                using (IModel failedQueue = OpenQueue(failedMachineName, userName, password))
                {
                    failedQueue.BasicPublish(string.Empty, failedQueueName, true, false, deliverArgs.BasicProperties, deliverArgs.Body);
                }
                errorQueue.BasicAck(deliverArgs.DeliveryTag, true);
            }
        }
        public void TestConsumerRecoveryWithManyConsumers()
        {
            string q = Model.QueueDeclare(GenerateQueueName(), false, false, false, null).QueueName;
            int n = 1024;

            for (int i = 0; i < n; i++)
            {
                var cons = new QueueingBasicConsumer(Model);
                Model.BasicConsume(q, true, cons);
            }

            var latch = new ManualResetEvent(false);
            ((AutorecoveringConnection)Conn).ConsumerTagChangeAfterRecovery += (prev, current) => latch.Set();

            CloseAndWaitForRecovery();
            Wait(latch);
            Assert.IsTrue(Model.IsOpen);
            AssertConsumerCount(q, n);
        }
 ///<summary>Creates a new Subscription, with full control over
 ///both "noAck" mode and the name of the queue.</summary>
 public Subscription(IModel model, string queueName, bool noAck)
 {
     Model = model;
     QueueName = queueName;
     NoAck = noAck;
     m_consumer = new QueueingBasicConsumer(Model);
     ConsumerTag = Model.BasicConsume(QueueName, NoAck, m_consumer);
     LatestEvent = null;
 }
        ///<summary>Closes this Subscription, cancelling the consumer
        ///record in the server.</summary>
        public void Close()
        {
            try
            {
                bool shouldCancelConsumer = false;

                if (m_consumer != null)
                {
                    shouldCancelConsumer = true;
                    m_consumer = null;
                }

                if (shouldCancelConsumer)
                {
                    if (Model.IsOpen)
                    {
                        Model.BasicCancel(ConsumerTag);
                    }

                    ConsumerTag = null;
                }
            }
            catch (OperationInterruptedException)
            {
                // We don't mind, here.
            }
        }
        static BasicDeliverEventArgs DequeueMessage(QueueingBasicConsumer consumer, int dequeueTimeout)
        {
            BasicDeliverEventArgs rawMessage;

            var messageDequeued = consumer.Queue.Dequeue(dequeueTimeout, out rawMessage);

            if (!messageDequeued)
            {
                return null;
            }

            return rawMessage;
        }
        void ConsumeMessages(object state)
        {
            if (!tracksRunningThreads.Wait(TimeSpan.FromSeconds(1)))
            {
                return;
            }

            try
            {
                var parameters = (ConsumeParams)state;
                var connection = connectionManager.GetConsumeConnection();

                using (var channel = connection.CreateModel())
                {
                    channel.BasicQos(0, actualPrefetchCount, false);

                    var consumer = new QueueingBasicConsumer(channel);

                    channel.BasicConsume(parameters.Queue, noAck,receiveOptions.ConsumerTag, consumer);

                    circuitBreaker.Success();

                    while (!parameters.CancellationToken.IsCancellationRequested)
                    {
                        Exception exception = null;
                        var message = DequeueMessage(consumer, receiveOptions.DequeueTimeout);

                        if (message == null)
                        {
                            continue;
                        }

                        TransportMessage transportMessage = null;

                        try
                        {
                            var messageProcessedOk = false;

                            try
                            {
                                transportMessage = receiveOptions.Converter.ToTransportMessage(message);
                            }
                            catch (Exception ex)
                            {
                                Logger.Error("Poison message detected, deliveryTag: " + message.DeliveryTag, ex);

                                //just ack the poison message to avoid getting stuck
                                messageProcessedOk = true;
                            }

                            if (transportMessage != null)
                            {
                                messageProcessedOk = tryProcessMessage(transportMessage);
                            }

                            if (!noAck)
                            {
                                if (messageProcessedOk)
                                {
                                    channel.BasicAck(message.DeliveryTag, false);
                                }
                                else
                                {
                                    channel.BasicReject(message.DeliveryTag, true);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            exception = ex;

                            if (!noAck)
                            {
                                channel.BasicReject(message.DeliveryTag, true);
                            }
                        }
                        finally
                        {
                            endProcessMessage(transportMessage, exception);
                        }
                    }
                }
            }
            catch (EndOfStreamException)
            {
                // If no items are present and the queue is in a closed
                // state, or if at any time while waiting the queue
                // transitions to a closed state (by a call to Close()), this
                // method will throw EndOfStreamException.

                // We need to put a delay here otherwise we end-up doing a tight loop that causes
                // CPU spikes
                Thread.Sleep(1000);
                throw;
            }
            catch (IOException)
            {
                //Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
                //This exception is expected because we are shutting down!
                if (!isStopping)
                {
                    throw;
                }
            }
            finally
            {
                tracksRunningThreads.Release();
            }
        }
 private void HandleConsumerCancelled(object sender, ConsumerEventArgs e)
 {
     lock (m_eventLock)
     {
         m_consumer = null;
         MutateLatestEvent(null);
     }
 }
 ///<summary>Creates a new Subscription, with full control over
 ///both "noAck" mode, the name of the queue, and the consumer tag.</summary>
 public Subscription(IModel model, string queueName, bool noAck, string consumerTag)
 {
     Model = model;
     QueueName = queueName;
     NoAck = noAck;
     m_consumer = new QueueingBasicConsumer(Model);
     m_consumer.ConsumerCancelled += HandleConsumerCancelled;
     ConsumerTag = Model.BasicConsume(QueueName, NoAck, consumerTag, m_consumer);
     LatestEvent = null;
 }
        public override void Open(TimeSpan timeout)
        {
            if (State != CommunicationState.Created && State != CommunicationState.Closed)
                throw new InvalidOperationException(string.Format("Cannot open the channel from the {0} state.",
                                                                  base.State));

            OnOpening();
            #if VERBOSE
            DebugHelper.Start();
            #endif
            RabbitMQUri uri = new RabbitMQUri(LocalAddress.Uri);

            m_model = ConnectionManager.Instance.OpenModel(uri, m_bindingElement.BrokerProtocol, timeout);

            string queue = uri.Endpoint;

            IDictionary args = new Dictionary<String, Object>();

            int ttl;
            if (!string.IsNullOrEmpty(m_bindingElement.TTL) && int.TryParse(m_bindingElement.TTL, out ttl))
            {
                args.Add("x-message-ttl", ttl);
            }

            //Create a queue for messages destined to this service, bind it to the service URI routing key
            queue = m_model.QueueDeclare(queue, true, false, m_autoDelete, args);

            if (!string.IsNullOrEmpty(m_bindToExchange))
            {
                m_model.QueueBind(queue, m_bindToExchange, uri.RoutingKey);
            }

            QueueingBasicConsumerBase queueingBasicConsumer;

            // Create queue
            if (m_bindingElement.TransactedReceiveEnabled)
            {
                queueingBasicConsumer = new TransactionalQueueConsumer(m_model);
            }
            else
            {
                queueingBasicConsumer = new QueueingBasicConsumer(m_model);
            }

            m_messageQueue = queueingBasicConsumer;

            //Listen to the queue
            bool noAck = !m_bindingElement.TransactedReceiveEnabled;

            m_model.BasicConsume(queue, noAck, queueingBasicConsumer);

            #if VERBOSE
            DebugHelper.Stop(" ## In.Channel.Open {{\n\tAddress={1}, \n\tTime={0}ms}}.", LocalAddress.Uri.PathAndQuery);
            #endif
            OnOpened();
        }
        void Action(object obj)
        {
            try
            {
                var cancellationToken = (CancellationToken) obj;
                var connection = ConnectionManager.GetConsumeConnection();

                using (var channel = connection.CreateModel())
                {
                    channel.BasicQos(0, PrefetchCount, false);

                    var consumer = new QueueingBasicConsumer(channel);

                    channel.BasicConsume(workQueue, autoAck, consumer);

                    circuitBreaker.Success();

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        Exception exception = null;
                        var message = DequeueMessage(consumer);

                        if (message == null)
                        {
                            continue;
                        }

                        TransportMessage transportMessage = null;

                        try
                        {
                            var messageProcessedOk = false;

                            try
                            {
                                transportMessage = RabbitMqTransportMessageExtensions.ToTransportMessage(message);
                            }
                            catch (Exception ex)
                            {
                                Logger.Error("Poison message detected, deliveryTag: " + message.DeliveryTag, ex);

                                //just ack the poison message to avoid getting stuck
                                messageProcessedOk = true;
                            }

                            if (transportMessage != null)
                            {
                                messageProcessedOk = tryProcessMessage(transportMessage);
                            }

                            if (!autoAck)
                            {
                                if (messageProcessedOk)
                                {
                                    channel.BasicAck(message.DeliveryTag, false);
                                }
                                else
                                {
                                    channel.BasicReject(message.DeliveryTag, true);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            exception = ex;

                            if (!autoAck)
                            {
                                channel.BasicReject(message.DeliveryTag, true);
                            }
                        }
                        finally
                        {
                            endProcessMessage(transportMessage, exception);
                        }
                    }
                }
            }
            finally
            {
                countdownEvent.Signal();
            }
        }
        public void TestThatCancelledConsumerDoesNotReappearOnRecovery()
        {
            string q = Model.QueueDeclare(GenerateQueueName(), false, false, false, null).QueueName;
            int n = 1024;

            for (int i = 0; i < n; i++)
            {
                var cons = new QueueingBasicConsumer(Model);
                string tag = Model.BasicConsume(q, true, cons);
                Model.BasicCancel(tag);
            }
            CloseAndWaitForRecovery();
            Assert.IsTrue(Model.IsOpen);
            AssertConsumerCount(q, 0);
        }
 public void TestDeclarationOfManyAutoDeleteQueuesWithTransientConsumer()
 {
     AssertRecordedQueues((AutorecoveringConnection)Conn, 0);
     for (int i = 0; i < 1000; i++)
     {
         string q = Guid.NewGuid().ToString();
         Model.QueueDeclare(q, false, false, true, null);
         var dummy = new QueueingBasicConsumer(Model);
         string tag = Model.BasicConsume(q, true, dummy);
         Model.BasicCancel(tag);
     }
     AssertRecordedQueues((AutorecoveringConnection)Conn, 0);
 }
        static BasicDeliverEventArgs DequeueMessage(QueueingBasicConsumer consumer)
        {
            BasicDeliverEventArgs rawMessage;

            if (!consumer.Queue.Dequeue(1000, out rawMessage))
            {
                return null;
            }

            return rawMessage;
        }
예제 #47
0
        /// <summary>
        /// The build queueing consumer.
        /// </summary>
        /// <returns>
        /// The <see cref="QueueingBasicConsumer"/>.
        /// </returns>
        public QueueingBasicConsumer BuildQueueingConsumer()
        {
            var consumer = new QueueingBasicConsumer(this.Native);

            /* if total reconnection is more desirable
                consumer.ConsumerCancelled += (sender, args) =>
                Failed(this, new ErrorEventArgs(new RabbitException("Consumer [{0}] was cancelled.".FormatEx(args.ConsumerTag))));
            */
            return consumer;
        }
        BasicDeliverEventArgs Consume(string id)
        {

            using (var channel = connectionManager.GetConsumeConnection().CreateModel())
            {
                var consumer = new QueueingBasicConsumer(channel);

                channel.BasicConsume("testEndPoint", false, consumer);

                BasicDeliverEventArgs message;

                if (!consumer.Queue.Dequeue(1000, out message))
                    throw new InvalidOperationException("No message found in queue");

                var e = message;

                if (e.BasicProperties.MessageId != id)
                    throw new InvalidOperationException("Unexpected message found in queue");

                channel.BasicAck(e.DeliveryTag,false);

                return e;
            }
        }