Simple IBasicConsumer implementation that uses a SharedQueue to buffer incoming deliveries.

Received messages are placed in the SharedQueue as instances of BasicDeliverEventArgs.

Note that messages taken from the SharedQueue may need acknowledging with IModel.BasicAck.

When the consumer is closed, through BasicCancel or through the shutdown of the underlying IModel or IConnection, the SharedQueue's Close() method is called, which causes any Enqueue() operations, and Dequeue() operations when the queue is empty, to throw EndOfStreamException (see the comment for SharedQueue.Close()).

The following is a simple example of the usage of this class:

IModel channel = ...; QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(queueName, null, consumer); // At this point, messages will be being asynchronously delivered, // and will be queueing up in consumer.Queue. while (true) { try { BasicDeliverEventArgs e = (BasicDeliverEventArgs) consumer.Queue.Dequeue(); // ... handle the delivery ... channel.BasicAck(e.DeliveryTag, false); } catch (EndOfStreamException ex) { // The consumer was cancelled, the model closed, or the // connection went away. break; } }
상속: DefaultBasicConsumer
예제 #1
1
 public Telegraph()
 {
     var connectionFactory = new ConnectionFactory { HostName = "localhost", VirtualHost = "test" };
     _connection = connectionFactory.CreateConnection();
     _channel = _connection.CreateModel();
     _consumer = new QueueingBasicConsumer(_channel);
 }
예제 #2
0
        public void Intitialize()
        {
            var factory = new ConnectionFactory { HostName = "localhost" };
            using(var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare("Aimbase.Events", "direct");
                var consumer = new QueueingBasicConsumer(channel);

                foreach (var evnt in _eventHandlers)
                {
                    var queueName = channel.QueueDeclare().QueueName;

                    channel.QueueBind(queueName, "Aimbase.Events", evnt.Type);

                    channel.BasicConsume(queueName, true, consumer);
                }

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

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);

                    foreach (var eventHandler in _eventHandlers.Where(eh => eh.Type == ea.RoutingKey))
                    {
                        eventHandler.Handle(message);
                    }
                }
            }
        }
예제 #3
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Ready to start charging for orders - press <enter> to stacking up cash...");
            Console.ReadLine();

            var factory = new ConnectionFactory { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    var queueName = channel.QueueDeclare().QueueName;
                    channel.QueueBind(queueName, ExchangeName, "");

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

                    Console.WriteLine("Waiting for work - press <ctrl-c> to shut down...");
                    while (true)
                    {
                        var message = consumer.Queue.Dequeue();

                        var body = message.Body;
                        var contents = Encoding.UTF8.GetString(body);

                        int quantity = int.Parse(contents.Split(' ')[0]);
                        Console.WriteLine("Charging for {0} widgets.", quantity);
                    }
                }
            }
        }
예제 #4
0
		private static void Main(string[] args)
		{
			var factory = new ConnectionFactory
			{
				HostName = "localhost",
				UserName = "******",
				Password = "******",
				Protocol = Protocols.DefaultProtocol
			};

			using (var c = factory.CreateConnection())
			using (var m = c.CreateModel())
			{
				var consumer = new QueueingBasicConsumer(m);
				var props = new Dictionary<string, object>()
				{
				    {"x-expires", 30*60000} // expire queue after 30 minutes, see http://www.rabbitmq.com/extensions.html
				};
				var q = m.QueueDeclare("", false, true, false, props);

				m.QueueBind(q, "log4net-logging", "#");
				m.BasicConsume(q, true, consumer);
				
				while (true)
				{
					var msg = (BasicDeliverEventArgs) consumer.Queue.Dequeue();
					
					if (msg.BasicProperties.IsAppIdPresent())
						Console.Write(msg.BasicProperties.AppId + " ");

					Console.Write(msg.Body.AsUtf8String());
				}
			}
		}
        private static void WorkerThreadFunc()
        {
            var factory = new ConnectionFactory { HostName = "127.0.0.1" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {

                // mark all messages as persistent
                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
                const bool autoAck = false;
                channel.BasicConsume(QueueName, autoAck, consumer);

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

                    byte[] body = ea.Body;
                    var message = System.Text.Encoding.UTF8.GetString(body);

                    Thread.Sleep(5000);

                    channel.BasicAck(ea.DeliveryTag, false);
                }
            }
        }
예제 #6
0
        public Task<PollerResult<Event>> NextAsync(QueueName name)
        {
            var connection = _connectionProvider.GetConnection();
            var result = new PollerResult<Event>(false , Event.Empty);
            using (var channel = connection.CreateModel())
            {
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(name.SubscriptionName, true, consumer);
                BasicDeliverEventArgs eventArgs = null;
                if (consumer.Queue.Dequeue((int)_longPollingTimeout.TotalMilliseconds, 
                    out eventArgs))
                {
                    var @event = new Event()
                    {
                        Body = Encoding.UTF8.GetString(eventArgs.Body),
                        QueueName = name.SubscriptionName,
                        UnderlyingMessage = eventArgs,
                        ContentType = "text/plain", // should it be JSON?
                        EventType = name.SubscriptionName
                    };

                    result = new PollerResult<Event>(true, @event);
                }
                return Task.FromResult(result);
            }

        }
예제 #7
0
파일: Receiver.cs 프로젝트: 3agrey/RabbitMQ
        public static void Main()
        {
            ConnectionFactory factory = new ConnectionFactory();
            factory.HostName = "localhost";
            using (IConnection connection = factory.CreateConnection())
            using (IModel channel = connection.CreateModel())
            {
                channel.QueueDeclare("start", false, false, false, null);

                QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume("start", true, consumer);

                System.Console.WriteLine(" [*] Waiting for messages." +
                                         "To exit press CTRL+C");
                while (true)
                {
                    BasicDeliverEventArgs ea =
                        (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    byte[] body = ea.Body;
                    string message = System.Text.Encoding.UTF8.GetString(body);
                    System.Console.WriteLine(" [x] Received {0}", message);
                }
            }
        }
예제 #8
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Logger waiting for messages...");

            var factory = new ConnectionFactory { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(ExchangeName, "topic");

                    var queueName = channel.QueueDeclare().QueueName;
                    channel.QueueBind(queueName, ExchangeName, "ewk.#");

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

                    int logEntry = 0;
                    Console.WriteLine("Waiting for work - press <ctrl-c> to shut down...");
                    while (true)
                    {
                        var message = consumer.Queue.Dequeue();

                        var body = message.Body;
                        var contents = Encoding.UTF8.GetString(body);

                        Console.WriteLine("[{0}:{1:yyyyMMdd-HHmmss.fffff}] {2}",
                            logEntry++, DateTimeOffset.Now, contents);
                    }
                }
            }
        }
예제 #9
0
    /*
        This method is receiving request from the server
    */
    public void receive()
    {
        DateTime date_ini = DateTime.Now;
        this.factory.HostName = c_reader.GetServer();

        using (var connection = this.factory.CreateConnection())
        {

            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare("transmission", "fanout");

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queueName, "transmission", "");

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

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

                while (true)
                {
                    var event_args = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    var body = event_args.Body;
                    var message = Encoding.UTF8.GetString(body);

                    Console.WriteLine(" [x] {0}", message);
                    //method to storage the message into the database
                    StoreData(message);

                }
            }
        }
    }
예제 #10
0
        static void Main()
        {
            _factory = new ConnectionFactory { HostName = "localhost", UserName = "******", Password = "******" };
            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    channel.ExchangeDeclare(ExchangeName, "direct");
                    channel.QueueDeclare(CardPaymentQueueName, true, false, false, null);
                    channel.QueueBind(CardPaymentQueueName, ExchangeName, "CardPayment");
                    channel.BasicQos(0, 1, false);

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

                    while (true)
                    {                        
                        var ea = consumer.Queue.Dequeue();
                        var message = (Payment)ea.Body.DeSerialize(typeof(Payment));                        
                        var routingKey = ea.RoutingKey;
                        channel.BasicAck(ea.DeliveryTag, false);
                        Console.WriteLine("--- Payment - Routing Key <{0}> : {1} : {2}", routingKey, message.CardNumber, message.AmountToPay);
                    }
                }
            }
        }
예제 #11
0
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using( var connection = factory.CreateConnection() )
        using( var channel = connection.CreateModel() )
        {
            channel.QueueDeclare( queue: "task_queue", durable: true, exclusive: false, autoDelete: false, arguments: null );

            channel.BasicQos( prefetchSize: 0, prefetchCount: 1, global: false );
            var consumer = new QueueingBasicConsumer( channel );
            channel.BasicConsume( queue: "task_queue", noAck: false, consumer: consumer );

            Console.WriteLine( " [*] Waiting for messages. To exit press CTRL+C" );
            while( true )
            {
                var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

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

                int dots = message.Split( '.' ).Length - 1;
                Thread.Sleep( dots * 1000 );

                Console.WriteLine( " [x] Done" );

                channel.BasicAck( deliveryTag: ea.DeliveryTag, multiple: false );
            }
        }
    }
예제 #12
0
        public void Run()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: "perf", type: "fanout");

                    var queueName = channel.QueueDeclare().QueueName;

                    channel.QueueBind(queue: queueName, exchange: "perf", routingKey: "");
                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, true, consumer);

                    Console.WriteLine(" [*] Waiting for perf. To exit press CTRL+C");
                    timer.Start();
                    while (true)
                    {
                        var ea = consumer.Queue.Dequeue();

                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        receivedMessages += 1;
                    }
                }
            }
        }
예제 #13
0
        private void ConsumeMessages(string queueName)
        {
            using (IConnection conn = factory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, false, consumer);
                    Trace.WriteLine(string.Format("Waiting for messages from: {0}", queueName));

                    while (true)
                    {
                        BasicDeliverEventArgs ea = null;
                        try
                        {
                            ea = consumer.Queue.Dequeue();
                        }
                        catch (EndOfStreamException endOfStreamException)
                        {
                            Trace.WriteLine(endOfStreamException);
                        }
                        if (ea == null) break;
                        var body = ea.Body;
                        var receivedMessage = _serializer.Deserialie<NotificationMessage>(body);
                        Trace.WriteLine(
                            string.Format(
                                "Message Received: {0} From: {1}, To: {2} on Thread: {3} with CorrelationId: {4} and DeliveryTag: {5}",
                                receivedMessage.Message, receivedMessage.Source, receivedMessage.Target,
                                Thread.CurrentThread.ManagedThreadId, ea.BasicProperties.CorrelationId, ea.DeliveryTag));
                        Thread.Sleep(300);
                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                }
            }
        }
예제 #14
0
        private static void ReceiveDotNetObjects(IModel model)
        {
            model.BasicQos(0, 1, false);
            QueueingBasicConsumer consumer = new QueueingBasicConsumer(model);
            model.BasicConsume(CommonService.DotNetObjectQueueName, false, consumer);
            while (true)
            {

                BasicDeliverEventArgs deliveryArguments = consumer.Queue.Dequeue() as BasicDeliverEventArgs;
                string objectType = deliveryArguments.BasicProperties.Type;
                Type t = Type.GetType(objectType);
                String jsonified = Encoding.UTF8.GetString(deliveryArguments.Body);
                object rawObject = JsonConvert.DeserializeObject(jsonified, t);
                Console.WriteLine("Object type: {0}", objectType);

                if (rawObject.GetType() == typeof(Customer))
                {
                    Customer customer = rawObject as Customer;
                    Console.WriteLine("Customer name: {0}", customer.Name);
                }
                else if (rawObject.GetType() == typeof(NewCustomer))
                {
                    NewCustomer newCustomer = rawObject as NewCustomer;
                    Console.WriteLine("NewCustomer name: {0}", newCustomer.Name);
                }
                model.BasicAck(deliveryArguments.DeliveryTag, false);
            }
        }
예제 #15
0
        static void Main(string[] args)
        {
            var exchg = "socketIOdemo";
            var queue = "socketIOdemoNetQ";

            var ser = new JavaScriptSerializer();
            var factory = new ConnectionFactory();
            factory.Protocol = Protocols.FromEnvironment();
            factory.HostName = "localhost";
            using (var con = factory.CreateConnection())
            using (var mod = con.CreateModel())
            {
                mod.QueueDeclare(queue, true, false, false, null);
                mod.ExchangeDeclare(exchg, ExchangeType.Fanout, true);
                mod.QueueBind(queue, exchg, string.Empty);

                var consumer = new QueueingBasicConsumer(mod);
                mod.BasicConsume(queue, false, consumer);
                Console.WriteLine("Waiting for messages...");
                while (true)
                {
                    var e = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    mod.BasicAck(e.DeliveryTag, false);
                    var props = e.BasicProperties;
                    byte[] body = e.Body;
                    var msg = ser.Deserialize<Message>(Encoding.UTF8.GetString(body));
                    Console.WriteLine(DateTime.Now.ToShortTimeString()+">> " + msg.body);
                }
            }
        }
예제 #16
0
        static void Main1()
        {
            var connectionFactory = new ConnectionFactory
            {
                HostName = "localhost"
            };

            using (IConnection connection = connectionFactory.CreateConnection())
            using (IModel chanell = connection.CreateModel())
            {
                chanell.QueueDeclare(queueName, false, false, false, null);

                var consumer = new QueueingBasicConsumer(chanell);
                chanell.BasicConsume(queueName, false, consumer);

                while (true)
                {
                    var message = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    var body = Encoding.UTF8.GetString(message.Body);

                    Console.WriteLine("Received message: " + body);
                    //
                    chanell.BasicAck(message.DeliveryTag, false);
                }
            }
        }
예제 #17
0
        private void MakeReplyConsumer()
        {
            replyQueueName = this.channel.QueueDeclare();

            replyConsumer = new QueueingBasicConsumer(this.channel);
            this.channel.BasicConsume(replyQueueName, true, replyConsumer);
        }
예제 #18
0
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare("task_queue", true, false, false, null);

                channel.BasicQos(0, 1, false);
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume("task_queue", false, consumer);

                Console.WriteLine(" [*] Waiting for messages. " +
                                  "To exit press CTRL+C");
                while (true)
                {
                    var ea =
                        (BasicDeliverEventArgs)consumer.Queue.Dequeue();

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

                    int dots = message.Split('.').Length - 1;
                    Thread.Sleep(dots * 1000);

                    Console.WriteLine(" [x] Done");

                    channel.BasicAck(ea.DeliveryTag, false);
                }
            }
        }
    }
예제 #19
0
        public override void Test(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare("logs", "fanout");

                    var queueName = channel.QueueDeclare().QueueName;
                    //The meaning of a binding key depends on the exchange type. The fanout exchanges,
                    //which we used previously, simply ignored its value
                    channel.QueueBind(queueName, "logs", "");
                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(queueName, true, consumer);

                    Console.WriteLine("接收消息:");
                    while (true)
                    {
                        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine("Recevied:" + message);
                    }
                }
            }
        }
예제 #20
0
 //https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/Worker/Worker.cs
 static void Dequeue(string queueName, string hostName, int expected)
 {
     int count = 0;
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     var factory = new ConnectionFactory() { HostName = hostName };
     factory.UserName = "******";
     factory.Password = "******";
     using (var connection = factory.CreateConnection())
     {
         using (var channel = connection.CreateModel())
         {
             channel.QueueDeclare(queueName, true, false, false, null);
             channel.BasicQos(0, 1, false);
             var consumer = new QueueingBasicConsumer(channel);
             channel.BasicConsume(queueName, false, consumer);
             sw.Start();
             while (count < expected)
             {
                 BasicDeliverEventArgs ea = consumer.Queue.Dequeue();
                 var body = ea.Body;
                 var message = Encoding.UTF8.GetString(body);
                 channel.BasicAck(ea.DeliveryTag, false);
                 ++count;
             }
             sw.Stop();
         }
     }
     Console.WriteLine(" [x] {0} messages dequeued in time = {1} ms", count, sw.ElapsedMilliseconds);
 }
예제 #21
0
        private static void Main()
        {
            Console.WriteLine("Ready to start shipping orders!");

            var factory = new ConnectionFactory {HostName = "localhost"};
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(QueueName, false, false, false, null);

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

                    Console.WriteLine("Waiting for work - press <ctrl-c> to shut down...");
                    while (true)
                    {
                        var message = consumer.Queue.Dequeue();

                        var body = message.Body;
                        var contents = Encoding.UTF8.GetString(body);

                        int quantity = int.Parse(contents.Split(' ')[0]);
                        Console.WriteLine("Shipping {0} widgets.", quantity);
                    }
                }
            }
        }
예제 #22
0
        static void Main(string[] args)
        {
            var connectionFactory = new ConnectionFactory();
            IConnection connection = connectionFactory.CreateConnection();
            IModel channel = connection.CreateModel();

            channel.ExchangeDeclare("topic-exchange-example", ExchangeType.Topic, false, true, null);
            channel.QueueDeclare("log", false, false, true, null);
            channel.QueueBind("log", "topic-exchange-example", "*.Personal.*");

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

            Console.WriteLine("I am the Personal Consumer");

            while (true)
            {
                try
                {
                    var eventArgs = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    string message = Encoding.UTF8.GetString(eventArgs.Body);
                    Console.WriteLine(string.Format("{0} - {1}", eventArgs.RoutingKey, message));
                }
                catch (EndOfStreamException)
                {
                    // The consumer was cancelled, the model closed, or the connection went away.
                    break;
                }
            }

            channel.Close();
            connection.Close();
        }
예제 #23
0
 public void Consume()
 {
     var consumer = new QueueingBasicConsumer(Model);
     consumerTag = Model.BasicConsume(queueName, false, consumer);
     while (isConsuming)
     {
         try
         {
             var e = consumer.Queue.Dequeue();
             OnReceiveMessage(new BasicDeliveryEventArgs(e));
             Model.BasicAck(e.DeliveryTag, false);
         }
         catch (OperationInterruptedException oiex)
         {
             Log.Error(oiex, "RabbitMqConsumer: Consume - the connection to the queue {0} has been lost", queueName);
             isConsuming = false;
             OnConsumerFailed();
             break;
         }
         catch (EndOfStreamException eose)
         {
             Log.Error(eose, "RabbitMqConsumer: Consume - the connection to the queue {0} has been closed", queueName);
             isConsuming = false;
             OnConsumerFailed();
             break;
         }
     }
 }
예제 #24
0
파일: Consumer.cs 프로젝트: juanlurie/Tools
        public void Consume()
        {
            var consumer = new QueueingBasicConsumer(Model);
            Model.BasicConsume(QueueName, false, consumer);
            while (IsConsuming)
            {
                try
                {
                    var e = (BasicDeliverEventArgs) consumer.Queue.Dequeue();
                    byte[] body = e.Body;
                    // ... process the message
                    OnMessageReceived(body);
                    Model.BasicAck(e.DeliveryTag, false);
                }
                catch (OperationInterruptedException ex)
                {
                    // The consumer was removed, either through
                    // channel or connection closure, or through the
                    // action of IModel.BasicCancel().
                    break;
                }
                catch (Exception ex)
                {

                }
            }
        }
예제 #25
0
        public int GetMQAlarmID()
        {
            int alarmID = 0;

            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "alarm",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                    var consumer = new QueueingBasicConsumer(channel);

                    channel.BasicConsume(queue: "alarm",
                                    noAck: true,
                                    consumer: consumer);

                    var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    alarmID = Convert.ToInt32(message);
                }
            }
            return alarmID;
        }
        public void Consume()
        {
            QueueingBasicConsumer consumer = new QueueingBasicConsumer(Model);
            String consumerTag = Model.BasicConsume(QueueName, false, consumer);
            while (isConsuming)
            {
                try
                {
                    RabbitMQ.Client.Events.BasicDeliverEventArgs e = (RabbitMQ.Client.Events.BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    IBasicProperties props = e.BasicProperties;
                    byte[] body = e.Body;
                    // ... process the message
                    onMessageReceived(body);
                    Model.BasicAck(e.DeliveryTag, false);
                }
                catch (OperationInterruptedException ex)
                {
                    // The consumer was removed, either through
                    // channel or connection closure, or through the
                    // action of IModel.BasicCancel().
                    break;
                }
            }

        }
예제 #27
0
        static void Main(string[] args)
        {
            if (args.Length < 1 || args.Length > 2)
            {
                Console.WriteLine("EasyNetQ.LogReader");
                Console.WriteLine("Usage:");
                Console.WriteLine("EasyNetQ.LogReader.exe <rabbitMqServer> [<vhost>]");
                return;
            }

            var connectionFactory = new ConnectionFactory
            {
                HostName = args[0],
                VirtualHost = args.Length == 2 ? args[1] : "/"
            };

            using (var connection = connectionFactory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(
                    logReaderQueue, // name
                    false,          // durable
                    true,           // exclusive
                    true,           // autoDelete
                    null);          // arguments

                channel.QueueBind(logReaderQueue, amqpLogExchange, "*");

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

                Console.WriteLine("EasyNetQ.LogReader");
                Console.WriteLine("Listening to log");

                while (true)
                {
                    try
                    {
                        var e = (RabbitMQ.Client.Events.BasicDeliverEventArgs) consumer.Queue.Dequeue();
                        var logMessage = Encoding.UTF8.GetString(e.Body);

                        Console.WriteLine(logMessage);

                        channel.BasicAck(e.DeliveryTag, false);
                    }
                    catch (Exception exception)
                    {
                        // The consumer was removed, either through
                        // channel or connection closure, or through the
                        // action of IModel.BasicCancel().

                        Console.WriteLine(exception);
                        Console.WriteLine();
                        Console.WriteLine("Connection closed.");

                        break;
                    }
                }
            }
        }
예제 #28
-1
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("hello", false, false, false, null);

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

                    Console.WriteLine(" [*] Waiting for messages." +
                                             "To exit press CTRL+C");
                    while (true)
                    {
                        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received {0}", message);
                    }
                }
            }
        }
예제 #29
-1
        public void TestWorkerReceive()
        {
            var factory = new ConnectionFactory { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare("hello", false, false, false, null);

                channel.BasicQos(0, 1, false);
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume("hello", true, consumer);

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

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);

                    int els = message.Split('l').Length - 1;
                    Thread.Sleep(els * 1000);

                    channel.BasicAck(ea.DeliveryTag, false);

                }
            }
        }
예제 #30
-1
파일: Program.cs 프로젝트: ZS/QueueTest
        public static void Main()
        {
            var factory = new ConnectionFactory();
            factory.HostName = "localhost";
            using (IConnection connection = factory.CreateConnection())
            using (IModel channel = connection.CreateModel())
            {
                channel.ExchangeDeclare("logs", "fanout");

                string queue_name = channel.QueueDeclare();

                channel.QueueBind(queue_name, "logs", "");
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(queue_name, true, consumer);

                Console.WriteLine(" [*] Waiting for logs." +
                                  "To exit press CTRL+C");
                while (true)
                {
                    var ea =
                        (BasicDeliverEventArgs)consumer.Queue.Dequeue();

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