Manages a subscription to a queue or exchange.

This convenience class abstracts away from much of the detail involved in receiving messages from a queue or an exchange.

Once created, the Subscription consumes from a queue (using a QueueingBasicConsumer). Received deliveries can be retrieved by calling Next(), or by using the Subscription as an IEnumerator in, for example, a foreach loop.

Note that if the "noAck" option is enabled (which it is by default), then received deliveries are automatically acked within the server before they are even transmitted across the network to us. Calling Ack() on received events will always do the right thing: if "noAck" is enabled, nothing is done on an Ack() call, and if "noAck" is disabled, IModel.BasicAck() is called with the correct parameters.

Inheritance: IEnumerable, IEnumerator, IDisposable
コード例 #1
1
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory
            {
                HostName = "localhost",
                UserName = "******",
                Password = "******",
            };

            var connection = factory.CreateConnection();

            var channel = connection.CreateModel();
            channel.QueueDeclare("LoanRequests", true, false, false, null);

            var subscription = new Subscription(channel, "LoanRequests", false);

            for (int i = 1; i < 10; i++)
            {
                var message = new LoanRequestMessage { Amount = i * 10000, Duration = i * 10, Ssn = 12312312 };
                channel.BasicPublish("", "LoanRequests", null, message.ToByteArray());
                Console.WriteLine("Created the following message: ");
                Console.WriteLine("SSN: " + message.Ssn);
                Console.WriteLine("Amount: " + message.Amount);
                Console.WriteLine("Duration: " + message.Duration);
            }

            Environment.Exit(0);
        }
コード例 #2
0
        public void ProcessMessages()
        {
            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    Console.WriteLine("Listening for Topic <payment.*>");
                    Console.WriteLine("------------------------------");
                    Console.WriteLine();
                    
                    channel.ExchangeDeclare(ExchangeName, "topic");
                    channel.QueueDeclare(AllQueueName, true, false, false, null);
                    channel.QueueBind(AllQueueName, ExchangeName, "payment.*");

                    channel.BasicQos(0, 10, false);
                    Subscription subscription = new Subscription(channel, AllQueueName, false);                    

                    while (true)
                    {
                        BasicDeliverEventArgs deliveryArguments = subscription.Next();
                        
                        var message = deliveryArguments.Body.DeSerializeText();

                        Console.WriteLine("Message Received '{0}'", message);
                        subscription.Ack(deliveryArguments);
                    }
                }
            }
        }
コード例 #3
0
ファイル: Subscriber.cs プロジェクト: heliocentric/dagent
        public static int Main(string[] args)
        {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: Subscriber <uri> [<message count>]");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return 2;
            }

            string serverAddress = args[0];
            long msgCount = (args.Length > 1) ? int.Parse(args[1]) : 10;
            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = serverAddress;
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    string queueName = ensureQueue(ch);

                    /* We'll consume msgCount message twice: once
                       using Subscription.Next() and once using the
                       IEnumerator interface.  So, we'll send out
                       2*msgCount messages. */
                    sendMessages(ch, queueName, 2*msgCount);
                    using (Subscription sub = new Subscription(ch, queueName)) {
                        blockingReceiveMessages(sub, msgCount);
                        enumeratingReceiveMessages(sub, msgCount);
                    }
                }
            }

            return 0;
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: Andorbal/rabbitmqplaytime
        static void Main(string[] args)
        {
            var cf = new ConnectionFactory();
            cf.Endpoint.HostName = "localhost";
            cf.Password = "******";
            cf.UserName = "******";
            using (IConnection conn = cf.CreateConnection())
            {
                using (IModel ch = conn.CreateModel())
                {
                    string queueName = ensureQueue(ch);

                    /* We'll consume msgCount message twice: once
                       using Subscription.Next() and once using the
                       IEnumerator interface.  So, we'll send out
                       2*msgCount messages. */
                    using (var sub = new Subscription(ch, queueName))
                    {
                        blockingReceiveMessages(sub, 100);
                    }
                }
            }

            return;
        }
コード例 #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitMqEventConsumer"/> class.
        /// </summary>
        /// <param name="connectionFactory">The connection factory.</param>
        /// <param name="exchangePath">The exchange path.</param>
        /// <param name="queue">The queue.</param>
        public RabbitMqEventConsumer(ConnectionFactory connectionFactory, string exchangePath, string queue)
        {
            _active = 1;
            _connection = connectionFactory.CreateConnection();
            _model = _connection.CreateModel();
            _queue = _model.QueueDeclare(queue, true, false, false, new Hashtable());

            // bind the queue to an exchange if specified
            if (exchangePath != null)
            {
                _model.QueueBind(_queue, exchangePath, string.Empty);
            }

            EventingBasicConsumer eventingBasicConsumer = new EventingBasicConsumer();
            eventingBasicConsumer.Received += HandleEvent;

            _model.BasicConsume(_queue, true, eventingBasicConsumer);

            #if false
            _subscription = new Subscription(_model, _queue, true);
            var thread = new Thread(ReceiveEvents);
            thread.IsBackground = true;
            thread.Name = "rabbitmq:consumer";
            thread.Start();
            #endif

            var uriBuilder = new UriBuilder(
                "rabbitmq",
                connectionFactory.HostName,
                connectionFactory.Port,
                queue);

            Uri = uriBuilder.Uri;
        }
コード例 #6
0
ファイル: RabbitMqMessageQueue.cs プロジェクト: karmerk/Rebus
        public RabbitMqMessageQueue(string connectionString, string inputQueueName)
        {
            this.inputQueueName = inputQueueName;

            Log.Info("Opening Rabbit connection");
            connection = new ConnectionFactory {Uri = connectionString}.CreateConnection();

            Log.Debug("Creating model");
            model = connection.CreateModel();

            Log.Info("Initializing exchange and input queue");
            var tempModel = connection.CreateModel();

            Log.Debug("Ensuring that exchange exists with the name {0}", ExchangeName);
            tempModel.ExchangeDeclare(ExchangeName, ExchangeType.Topic, true);

            Log.Debug("Declaring queue {0}", this.inputQueueName);
            tempModel.QueueDeclare(this.inputQueueName, true, false, false, new Hashtable());

            Log.Debug("Binding {0} to {1} (routing key: {2})", this.inputQueueName, ExchangeName, this.inputQueueName);
            tempModel.QueueBind(this.inputQueueName, ExchangeName, this.inputQueueName);

            Log.Debug("Opening subscription");
            subscription = new Subscription(model, inputQueueName);
        }
コード例 #7
0
        public void ProcessMessages()
        {
            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    Console.WriteLine("Listening for Topic <payment.purchaseorder>");
                    Console.WriteLine("------------------------------------------");
                    Console.WriteLine();
                    
                    channel.ExchangeDeclare(ExchangeName, "topic");
                    channel.QueueDeclare(PurchaseOrderQueueName, true, false, false, null);
                    channel.QueueBind(PurchaseOrderQueueName, ExchangeName, "payment.purchaseorder");

                    channel.BasicQos(0, 10, false);
                    Subscription subscription = new Subscription(channel, PurchaseOrderQueueName, false);
                    
                    while (true)
                    {
                        BasicDeliverEventArgs deliveryArguments = subscription.Next();

                        var message = (PurchaseOrder)deliveryArguments.Body.DeSerialize(typeof(PurchaseOrder));
                        var routingKey = deliveryArguments.RoutingKey;

                        Console.WriteLine("-- Purchase Order - Routing Key <{0}> : {1}, £{2}, {3}, {4}", routingKey, message.CompanyName, message.AmountToPay, message.PaymentDayTerms, message.PoNumber);
                        subscription.Ack(deliveryArguments);
                    }
                }
            }
        }
コード例 #8
0
    public void Subscribe(string queueName, Action<string> callback)
    {      
      this.Subscriptions = this.Subscriptions ?? Enumerable.Empty<Task>();
      this.Subscriptions = this.Subscriptions.Concat(new[] {
        Task.Factory.StartNew(delegate {
          var factory = new ConnectionFactory()
          {
            VirtualHost = "/",
            HostName = "127.0.0.1",
            Port = AmqpTcpEndpoint.UseDefaultPort
          };
          factory.UserName = "******";
          factory.Password = "******";

          using (var connection = factory.CreateConnection())
          {
            using (var channel = connection.CreateModel())
            {
              var subscription = new Subscription(channel, queueName, false);
              while(true)
              {
                var eventArgs = subscription.Next();
                var content = eventArgs == null ? string.Empty : Encoding.UTF8.GetString(eventArgs.Body);
                subscription.Ack(eventArgs);

                callback(content);
              }
            }
          }
        }
      )});
    }
コード例 #9
0
 public void Subscribe(string queueName)
 {
     ch.QueueBind(queueName, "amq.direct", queueName, false, null);
     using (Subscription sub = new Subscription(ch, queueName))
     {
         ReceiveMessages(sub);
     }
 }
コード例 #10
0
ファイル: RabbitListener.cs プロジェクト: DropZone/LogC
        public void StartListening(Action<byte[], IDictionary<string, object>> onMessage)
        {
            if (this.IsListening)
                throw new InvalidOperationException("Client is already listening for messages");

            Action subscribeAction =
                () =>
                {
                    try
                    {
                        subscriptionLifetimeResetEvent.Reset();
                        Subscription subscriptionHandler = new Subscription(this.Connection.GetModel(), this.QueueName);
                        int waitForMessagesTimeout = 100;

                        this.loopControlResetEvent.Reset();
                        while (!loopControlResetEvent.IsSet)
                        {
                            try
                            {
                                BasicDeliverEventArgs delivery = null;
                                if (subscriptionHandler.Next(waitForMessagesTimeout, out delivery))
                                {
                                    if (delivery == null)
                                        continue;

                                    // Deliver message
                                    var p = CreateProperties(delivery);
                                    onMessage(delivery.Body, p);
                                }

                            }
                            catch (ThreadAbortException)
                            {
                                // Nothing to do, thread is being aborted.
                                // Set the reset event to leave gracefully
                                loopControlResetEvent.Set();
                            }
                            catch (Exception)
                            {
                                // Any other exception should be ignored.
                            }
                        }

                        // Close the subscription if its still open
                        if (subscriptionHandler.Model.IsOpen)
                        {
                            subscriptionHandler.Close();
                        }
                    }
                    finally
                    {
                        subscriptionLifetimeResetEvent.Set();
                    }
                };

            this.currentSubscription = subscribeAction;
        }
コード例 #11
0
        private int OneConsumer()
        {
            using (var connection = Helpers.CreateConnectionToSecondaryVirtualHostOnAlternativePort())
            using (var model = connection.CreateModel())
            {
                var queue = model.QueueDeclare();
                model.QueueBind(queue, Constants.FederationExchangeName, "#");
                var subscription = new Subscription(model, queue, true);

                consumerReady.Set();

                return subscription.Next().Body.Integer();
            }
        }
コード例 #12
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public override void Dispose()
        {
            if (Interlocked.CompareExchange(ref _active, 1, 0) == 1)
            {
                _subscription.Close();
                _subscription = null;

                _model.Dispose();
                _model = null;

                _connection.Dispose();
                _connection = null;
            }
        }
        protected void TestSequentialIterationWithDrainer(Action<Subscription> action)
        {
            IDictionary<string, object> args = new Dictionary<string, object>
            {
                {Headers.XMessageTTL, 5000}
            };
            string queueDeclare = Model.QueueDeclare("", false, true, false, args);
            var subscription = new Subscription(Model, queueDeclare, false);

            PreparedQueue(queueDeclare);

            var drainer = new SubscriptionDrainer(subscription, action);
            drainer.Drain();
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: Andorbal/rabbitmqplaytime
        private static void blockingReceiveMessages(Subscription sub, long msgCount)
        {
            Console.WriteLine("Receiving {0} messages (using a Subscriber)", msgCount);

            for (int i = 0; i < msgCount; ++i)
            {
                Console.WriteLine("Message {0}: {1} (via Subscription.Next())",
                                  i, messageText(sub.Next()));
                Console.WriteLine("Message {0} again: {1} (via Subscription.LatestEvent)",
                                  i, messageText(sub.LatestEvent));
                sub.Ack();
            }

            Console.WriteLine("Done.\n");
        }
コード例 #15
0
		private void RunConsumer(
			string queueName)
		{
			new Task(() =>
				{
					var _channel = this.c_connection.CreateModel();

					var _consumer = new Subscription(_channel, queueName);
					foreach (BasicDeliverEventArgs _messageDelivery in _consumer)
					{
						this.c_writeLog(string.Format("Received message on q {0}, tag = {1}", queueName, _messageDelivery.DeliveryTag));
						_consumer.Ack(_messageDelivery);
					}
				}).Start();
		}
コード例 #16
0
 public void TestConsumerCancellationNotification()
 {
     var q = Guid.NewGuid().ToString();
     this.Model.QueueDeclare(queue: q, durable: false, exclusive: false, autoDelete: false, arguments: null);
     var sub = new Subscription(this.Model, q);
     var latch = new ManualResetEvent(false);
     sub.Consumer.ConsumerCancelled += (_sender, _args) =>
     {
         sub.Close();
         latch.Set();
         Conn.Close();
     };
     this.Model.QueueDelete(q);
     Wait(latch, TimeSpan.FromSeconds(4));
 }
コード例 #17
0
        private void Consume()
        {
            bool autoAck = false;

            //create a subscription
            mSubscription = new Subscription(Model, QueueName, autoAck);
           
            while (isConsuming)
            {
                BasicDeliverEventArgs e = mSubscription.Next();
                byte[] body = e.Body;
                onMessageReceived(body);
                mSubscription.Ack(e);

            }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: reckcn/RabbitMQ.Project
		static void Main()
		{
			// Set up the RabbitMQ connection and channel
			var connectionFactory = new ConnectionFactory
			{
				HostName = "localhost",
				Port = 5672,
				UserName = "******",
				Password = "******",
				Protocol = Protocols.AMQP_0_9_1,
				RequestedFrameMax = UInt32.MaxValue,
				RequestedHeartbeat = UInt16.MaxValue
			};

		    using (var connection = connectionFactory.CreateConnection())
		    {
                using (var channel = connection.CreateModel())
                {
                    // This instructs the channel not to prefetch more than one message
                    channel.BasicQos(0, 1, false);

                    // Create a new, durable exchange
                    channel.ExchangeDeclare("sample-ex", ExchangeType.Direct, true, false, null);
                    // Create a new, durable queue
                    channel.QueueDeclare("sample-queue", true, false, false, null);
                    // Bind the queue to the exchange
                    channel.QueueBind("sample-queue", "sample-ex", "optional-routing-key");

                    using (var subscription = new Subscription(channel, "sample-queue", false))
                    {
                        Console.WriteLine("Waiting for messages...");
                        var encoding = new UTF8Encoding();
                        while (channel.IsOpen)
                        {
                            BasicDeliverEventArgs eventArgs;
                            var success = subscription.Next(2000, out eventArgs);
                            if (success == false) continue;
                            var msgBytes = eventArgs.Body;
                            var message = encoding.GetString(msgBytes);
                            Console.WriteLine(message);
                            channel.BasicAck(eventArgs.DeliveryTag, false);
                        }
                    }
                }
            }
		}
コード例 #19
0
		public void Close ()
		{
			if (subscription != null) {
				subscription.Close ();
				subscription = null;
			}
			
			if (model != null) {
				model.Dispose ();
				model = null;
			}
			
			if (cn != null) {
				cn.Dispose ();
				cn = null;
			}
		}
コード例 #20
0
        /// <remarks>
        /// RabbitMq does not have a Peek feature, the solution is to dequeue all messages
        /// without acknowledging them (noAck = true). After all messages have been read
        /// we dispose the RabbitMqJobQueue causing the channel to close. All unack'd
        /// messages then get requeued in order.
        /// </remarks>
        public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage)
        {
            using (var client = new RabbitMqJobQueue(new[] {queue}, _factory))
            {
                var consumer = new Subscription(client.Channel, queue, true);

                List<int> jobIds = new List<int>();
                BasicDeliverEventArgs delivery;

                while (consumer.Next(1000, out delivery))
                {
                    var body = Encoding.UTF8.GetString(delivery.Body);
                    jobIds.Add(Convert.ToInt32(body));
                }

                return jobIds.Skip(@from).Take(perPage);
            }
        }
コード例 #21
0
        public static int Main(string[] args)
        {
            if (args.Length < 4) {
                Console.Error.WriteLine("Usage: LogTail <uri> <exchange> <exchangetype> <routingkey>");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine(" <uri> = \"amqp://*****:*****@host:port/vhost\"");
                Console.Error.WriteLine("If the exchange name is the empty string, will instead declare a queue named");
                Console.Error.WriteLine("by the routingkey, and consume from that queue.");
                return 2;
            }

            string serverAddress = args[0];
            string exchange = args[1];
            string exchangeType = args[2];
            string routingKey = args[3];

            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = serverAddress;

            using (IConnection conn = cf.CreateConnection())
                {
                    using (IModel ch = conn.CreateModel()) {
                        ch.QueueDeclare(routingKey, false, true, true, null);
                        Subscription sub = new Subscription(ch, routingKey);
                        if (exchange != "") {
                            ch.ExchangeDeclare(exchange, exchangeType);
                            ch.QueueBind(routingKey, exchange, routingKey, null);
                        }

                        Console.WriteLine("Consumer tag: " + sub.ConsumerTag);
                        foreach (BasicDeliverEventArgs e in sub) {
                            sub.Ack(e);
                            ProcessSingleDelivery(e);
                            if (Encoding.UTF8.GetString(e.Body) == "quit") {
                                Console.WriteLine("Quitting!");
                                break;
                            }
                        }

                        return 0;
                    }
                }
        }
コード例 #22
0
ファイル: Consumer.cs プロジェクト: gimmi/Log4Rabbit
 public static IEnumerable<LogData> GetAllMessages()
 {
     using (IConnection connection = SetUpFixture.ConnectionFactory.CreateConnection())
     {
         using (IModel model = connection.CreateModel())
         {
             var subscription = new Subscription(model, SetUpFixture.QueueName);
             BasicDeliverEventArgs basicDeliveryEventArgs;
             while (subscription.Next(1000, out basicDeliveryEventArgs))
             {
                 var logs = (Body) XmlSerializer.Deserialize(new MemoryStream(basicDeliveryEventArgs.Body));
                 foreach (var entry in logs.LogDatas)
                 {
                     yield return entry;
                 }
             }
         }
     }
 }
コード例 #23
0
ファイル: AddServer.cs プロジェクト: NashDotNet/rabbitlab
        public static int Main(string[] args)
        {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: AddServer <hostname>[:<portnumber>]");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                return 2;
            }

            ConnectionFactory cf = new ConnectionFactory();
            cf.Address = args[0];
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    ch.QueueDeclare("AddServer", false, false, false, null);
                    Subscription sub = new Subscription(ch, "AddServer");
                    new AddServer(sub).MainLoop();
                }
            }
            return 0;
        }
コード例 #24
0
        public static int Main(string[] args) {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: AddServer <uri>");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return 2;
            }

            ConnectionFactory cf = new ConnectionFactory();
            cf.Uri = args[0];
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    ch.QueueDeclare("AddServer", false, false, false, null);
                    Subscription sub = new Subscription(ch, "AddServer");
                    new AddServer(sub).MainLoop();
                }
            }
            return 0;
        }
コード例 #25
0
        public void Listen()
        {
            Console.WriteLine("Creating channel...");
            using (IModel model = conn.CreateModel())
            {
                var subscription = new Subscription(model, "queue", false);
                //while (true)
                //{
                    BasicDeliverEventArgs basicDeliveryEventArgs =
                        subscription.Next();
                    var command = StreamExtension.Deserialize<Vaccine.Core.Cqrs.Commands.DomainCommand>(basicDeliveryEventArgs.Body);

                    //Encoding.UTF8.GetString(basicDeliveryEventArgs.Body);
                    //Console.WriteLine(((CreateCommand)messageContent).Name);
                    bus.Send(command);

                    subscription.Ack(basicDeliveryEventArgs);
                //}
            }
        }
コード例 #26
0
        public void ReceiveHeadersMessageReceiverOne(IModel model)
        {
            model.BasicQos(0, 1, false);
            Subscription subscription = new Subscription(model, _headersQueueOne, false);
            while (true)
            {
                BasicDeliverEventArgs deliveryArguments = subscription.Next();
                StringBuilder messageBuilder = new StringBuilder();
                String message = Encoding.UTF8.GetString(deliveryArguments.Body);
                messageBuilder.Append("Message from queue: ").Append(message).Append(". ");
                foreach (string headerKey in deliveryArguments.BasicProperties.Headers.Keys)
                {
                    byte[] value = deliveryArguments.BasicProperties.Headers[headerKey] as byte[];
                    messageBuilder.Append("Header key: ").Append(headerKey).Append(", value: ").Append(Encoding.UTF8.GetString(value)).Append("; ");
                }

                Console.WriteLine(messageBuilder.ToString());
                subscription.Ack(deliveryArguments);
            }
        }
コード例 #27
0
        public static int Main(string[] args)
        {
            if (args.Length < 1) {
                Console.Error.WriteLine("Usage: ShutdownableServer <hostname>[:<portnumber>]");
                Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
                return 2;
            }

            ConnectionFactory cf = new ConnectionFactory();
            cf.Address = args[0];
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    Subscription sub = new Subscription(ch, "ShutdownableServer");
                    new ShutdownableServer(sub).MainLoop();
                    Console.Out.WriteLine("Returned from MainLoop.");
                }
            }
            Console.Out.WriteLine("Leaving the program.");
            return 0;
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: merbla/Presos
        public static void Main(string[] args)
        {
            var connectionFactory = new ConnectionFactory {HostName = Settings.RabbitMqHost};

            using (var connection = connectionFactory.CreateConnection())
            {
                using (var model = connection.CreateModel())
                {
                    var subscription = new Subscription(model, Settings.RabbitMqQueue, false);
                    while (true)
                    {
                        var basicDeliveryEventArgs = subscription.Next();
                        var messageContent = basicDeliveryEventArgs.Body.To<SimpleMessage>();
                        System.Console.WriteLine(messageContent.Content);
                        subscription.Ack(basicDeliveryEventArgs);
                    }
                }
            }

            System.Console.ReadLine();
        }
        public void TestChannelClosureIsObservableOnSubscription()
        {
            string q = Model.QueueDeclare();
            Subscription sub = new Subscription(Model, q, true);

            BasicDeliverEventArgs r1;
            Assert.IsFalse(sub.Next(100, out r1));

            Model.BasicPublish("", q, null, enc.GetBytes("a message"));
            Model.BasicPublish("", q, null, enc.GetBytes("a message"));

            BasicDeliverEventArgs r2;
            Assert.IsTrue(sub.Next(1000, out r2));
            Assert.IsNotNull(sub.Next());

            Model.Close();
            Assert.IsNull(sub.Next());

            BasicDeliverEventArgs r3;
            Assert.IsFalse(sub.Next(100, out r3));
        }
コード例 #30
0
 ///<summary>Create, but do not start, an instance that will
 ///receive requests via the given Subscription.</summary>
 ///<remarks>
 ///<para>
 /// The instance is initially in non-transactional mode. See
 /// SetTransactional().
 ///</para>
 ///<para>
 /// Call MainLoop() to start the request-processing loop.
 ///</para>
 ///</remarks>
 public SimpleRpcServer(Subscription subscription)
 {
     m_subscription  = subscription;
     m_transactional = false;
 }
コード例 #31
-1
        static void Main(string[] args)
        {
            try
            {
                ConnectionFactory cf = new ConnectionFactory();
                cf.Uri = "amqps://<user>:<pass>@<server>:5671/";
                cf.Ssl.CertPath = "C:\\keycert.p12";
                cf.Ssl.CertPassphrase = "<ClientCertPass>";
                cf.Ssl.Enabled = true;

                using (IConnection conn = cf.CreateConnection())
                {
                    Console.WriteLine("Connection established");
                    using (IModel ch = conn.CreateModel())
                    {
                        ch.BasicQos(0, 1, false);                                   // noAck
                        Subscription sub = new Subscription(ch, "QueueName", true); // last param MUST BE true
                        while (true)
                        {
                            BasicDeliverEventArgs e = sub.Next();
                            byte[] body = e.Body;
                            Console.WriteLine(Encoding.UTF8.GetString(body));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }