Example #1
0
        public void Should_throw_exception_if_delivery_tags_is_null()
        {
            var channel = Substitute.For<IModel>();
            channel.IsOpen.Returns(true);
            var subscription = new Subscription(channel);

            // Action
            subscription.Ack(null);
        }
Example #2
0
        public ReceivedTransportMessage ReceiveMessage(ITransactionContext context)
        {
            try
            {
                if (!context.IsTransactional)
                {
                    using (var localModel = GetConnection().CreateModel())
                    {
                        var basicGetResult = localModel.BasicGet(inputQueueName, true);

                        if (basicGetResult == null)
                        {
                            Thread.Sleep(BackoffTime);
                            return(null);
                        }

                        return(GetReceivedTransportMessage(basicGetResult.BasicProperties, basicGetResult.Body));
                    }
                }

                EnsureThreadBoundModelIsInitialized(context);

                if (threadBoundSubscription == null || !threadBoundSubscription.Model.IsOpen)
                {
                    threadBoundSubscription = new Subscription(threadBoundModel, inputQueueName, false);
                }

                BasicDeliverEventArgs ea;
                if (!threadBoundSubscription.Next((int)BackoffTime.TotalMilliseconds, out ea))
                {
                    return(null);
                }

                // wtf??
                if (ea == null)
                {
                    return(null);
                }

                context.BeforeCommit  += () => threadBoundSubscription.Ack(ea);
                context.AfterRollback += () =>
                {
                    threadBoundModel.BasicNack(ea.DeliveryTag, false, true);
                    threadBoundModel.TxCommit();
                };

                return(GetReceivedTransportMessage(ea.BasicProperties, ea.Body));
            }
            catch (Exception e)
            {
                ErrorOnConnection(e);
                throw;
            }
        }
        public void Listen(string queueName)
        {
            var subscription = new Subscription(_model, queueName, false);

            while (true)
            {
                Console.WriteLine("Listen");
                BasicDeliverEventArgs eventArgs = subscription.Next();
                OnGetMsg(eventArgs);
                subscription.Ack(eventArgs);
            }
        }
Example #4
0
        private void ListenUpdated(Subscription subscriptionUpdated)
        {
            BasicDeliverEventArgs eventArgsUpdated = subscriptionUpdated.Next();

            if (eventArgsUpdated != null)
            {
                string messageContent           = Encoding.UTF8.GetString(eventArgsUpdated.Body);
                ClienteAtualizadoEvent _updated = JsonConvert.DeserializeObject <ClienteAtualizadoEvent>(messageContent);
                _repository.Update(_updated.ToCustomerEntity(_repository.GetCustomer(_updated.Id)));
                subscriptionUpdated.Ack(eventArgsUpdated);
            }
        }
Example #5
0
        private void Poll()
        {
            while (Enabled)
            {
                var deliveryArgs = _subscription.Next();
                var message      = Encoding.Default.GetString(deliveryArgs.Body);

                Console.WriteLine("Message Recieved - {0}", message);

                _subscription.Ack(deliveryArgs);
            }
        }
Example #6
0
        private void ListenDeleted(Subscription subscriptionDeleted)
        {
            BasicDeliverEventArgs eventArgsDeleted = subscriptionDeleted.Next();

            if (eventArgsDeleted != null)
            {
                string messageContent         = Encoding.UTF8.GetString(eventArgsDeleted.Body);
                CustomerDeletedEvent _deleted = JsonConvert.DeserializeObject <CustomerDeletedEvent>(messageContent);
                _repository.Remove(_deleted.Id);
                subscriptionDeleted.Ack(eventArgsDeleted);
            }
        }
Example #7
0
        private void ListenCreated(Subscription subscriptionCreated)
        {
            BasicDeliverEventArgs eventArgsCreated = subscriptionCreated.Next();

            if (eventArgsCreated != null)
            {
                string messageContent         = Encoding.UTF8.GetString(eventArgsCreated.Body);
                CustomerCreatedEvent _created = JsonConvert.DeserializeObject <CustomerCreatedEvent>(messageContent);
                _repository.Create(_created.ToCustomerEntity());
                subscriptionCreated.Ack(eventArgsCreated);
            }
        }
        public void ProcessMessages()
        {
            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    Console.WriteLine("Listening for Topic <payment.cardpayment>");
                    Console.WriteLine("-----------------------------------------");
                    Console.WriteLine();

                    //idempotent operation: if the exchange already exists then it won't be recreated
                    channel.ExchangeDeclare(exchange: ExchangeName, type: "topic");

                    //idempotent operation
                    channel.QueueDeclare(queue: CardPaymentQueueName,
                                         durable: true, exclusive: false, autoDelete: false, arguments: null);

                    channel.QueueBind(queue: CardPaymentQueueName, exchange: ExchangeName,
                                      routingKey: "payment.cardpayment");

                    //the basic Qos with a prefix count = 1, i.e. consumer will reserve one message after queue
                    //to process at a time, If any of those messages are not acknowledged when they are finished processing,
                    //then they will be put back onto the queue ready for another consumer to process them.
                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
                    //channel.BasicQos(prefetchSize: 0, prefetchCount: 10, global: false);

                    //Subscription is a high level abstraction that has a more natural iterator feel to it.
                    //To use it we simply create a new instance and supply the channel
                    //and the queue which we want to get the messages from.
                    //noAck: false => consumer will acknowledge when it finishes processing
                    Subscription subscription = new Subscription(model: channel,
                                                                 queueName: CardPaymentQueueName, noAck: false);

                    while (true) //run an infinite loop to listen to messages in the queue
                    {
                        //we enter a while called next and the subscriptions get the next message
                        BasicDeliverEventArgs deliveryArguments = subscription.Next();

                        //The serialized message throughout the card payment or (a purchase order if it is a purchase order consumer).
                        var message = (CardPayment)deliveryArguments.Body.DeSerialize(typeof(CardPayment));

                        var routingKey = deliveryArguments.RoutingKey;

                        Console.WriteLine("--- Payment - Routing Key <{0}> : {1} : {2}", routingKey, message.CardNumber, message.Amount);

                        // Once we have finished with the message,we call the ACK method and the subscription
                        // to acknowledge the message
                        subscription.Ack(deliveryArguments);
                    }
                }
            }
        }
        public void ReceivePublishSubscribeMessageReceiverTwo(IModel model)
        {
            model.BasicQos(0, 1, false);
            Subscription subscription = new Subscription(model, _publishSubscribeQueueTwo, false);

            while (true)
            {
                BasicDeliverEventArgs deliveryArguments = subscription.Next();
                String message = Encoding.UTF8.GetString(deliveryArguments.Body);
                Console.WriteLine("Message from queue: {0}", message);
                subscription.Ack(deliveryArguments);
            }
        }
Example #10
0
        static void Main(string[] args)
        {
            const string MQ_HOST          = "crmdevapp01";
            const string MQ_USER_NAME     = "user";
            const string MQ_USER_PASSWORD = "******";
            const string MQ_EXCHANGE_NAME = "API";
            const string MQ_QUEUE_NAME    = "RS_Test";

            var factory = new ConnectionFactory {
                HostName = MQ_HOST, UserName = MQ_USER_NAME, Password = MQ_USER_PASSWORD, Port = AmqpTcpEndpoint.UseDefaultPort
            };

            using (var con = factory.CreateConnection())
                using (var channel = con.CreateModel())
                {
                    do
                    {
                        string response = null;

                        var correlationId = Guid.NewGuid().ToString();
                        var message       = Console.ReadLine();
                        channel.BasicPublish(
                            exchange: MQ_EXCHANGE_NAME,
                            routingKey: "Smev",
                            body: Encoding.UTF8.GetBytes(message),
                            basicProperties: new BasicProperties
                        {
                            ReplyTo       = MQ_QUEUE_NAME,
                            DeliveryMode  = 2,
                            CorrelationId = correlationId,
                            Headers       = new Dictionary <string, object> {
                                { "Method", "Test" }
                            }
                        }
                            );

                        var sub = new Subscription(channel, MQ_QUEUE_NAME, false);
                        foreach (BasicDeliverEventArgs e in sub)
                        {
                            if (e.BasicProperties.CorrelationId == correlationId)
                            {
                                response = e.GetMessage();
                                sub.Ack(e);
                                break;
                            }
                        }

                        Console.WriteLine(response);
                    } while (true);
                }
        }
Example #11
0
        public async Task <int> Listen(int timeout, CancellationToken cancellationToken)
        {
            try
            {
                var factory = new ConnectionFactory
                {
                    HostName = _defaultConfig.Hostname,
                    UserName = _defaultConfig.User,
                    Password = _defaultConfig.Password,
                    Port     = _defaultConfig.Port
                };
                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: _defaultConfig.TopicName,
                                             durable: _defaultConfig.Durable,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);

                        var messageCounter = 0;

                        var subscription = new Subscription(channel, _defaultConfig.TopicName, false);

                        var finishAt = DateTime.Now.AddSeconds(timeout);
                        while ((timeout == 0 || DateTime.Now < finishAt) && !cancellationToken.IsCancellationRequested)
                        {
                            subscription.Next(5000, out var basicDeliveryEventArgs);
                            if (basicDeliveryEventArgs != null)
                            {
                                string messageContent = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body);
                                _messageHandler.Handle(_defaultConfig.TopicName, messageContent);
                                subscription.Ack(basicDeliveryEventArgs);
                                if (timeout > 0) //count messages only if there is timeout defined
                                {
                                    messageCounter++;
                                }
                            }
                        }

                        await Task.Delay(timeout * 1000, cancellationToken);

                        return(await Task.FromResult(messageCounter));
                    }
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                throw;
            }
        }
Example #12
0
        /// <summary>
        /// Receive Messages
        /// </summary>
        /// <param name="queueName"></param>
        /// <param name="subject"></param>
        public async Task ReceiveMessages(string queueName, Subject <MessageQueue> subject, IMessageQueueProcessing _messageProcessor)
        {
            Console.WriteLine("Receiving Messages at " + DateTime.Now);

            if (_running == true)
            {
                return;
            }

            _running = true;

            var response = _channel.QueueDeclarePassive(queueName);

            _channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false, arguments: null);

            _subscription = new Subscription(_channel, queueName, false);

            foreach (BasicDeliverEventArgs e in _subscription)
            {
                string message = Encoding.UTF8.GetString(e.Body);

                MessageQueue messageQueue = JsonConvert.DeserializeObject <MessageQueue>(message);
                messageQueue.MessageGuid = Guid.NewGuid();

                if (messageQueue.QueueName == string.Empty || messageQueue.QueueName == null)
                {
                    messageQueue.QueueName = _originatingQueueName;
                }


                Console.WriteLine("Receiving Message id " + messageQueue.TransactionQueueId);

                ResponseModel <MessageQueue> responseMessage = await _messageProcessor.CommitInboundMessage(messageQueue, _connectionStrings);

                if (responseMessage.ReturnStatus == true)
                {
                    if (_sendToLoggingQueue == true)
                    {
                        responseMessage = SendReceivedMessageToLoggingQueue(messageQueue);
                    }

                    if (responseMessage.ReturnStatus == true)
                    {
                        Console.WriteLine($"Message Committed: {messageQueue.TransactionQueueId}");
                        _subscription.Ack(e);
                    }

                    await _messageProcessor.ProcessMessages(_inboundSemaphoreKey, _connectionStrings);
                }
            }
        }
Example #13
0
        public void SubscribeWithSubscriber()
        {
            WithChannel.Do(channel =>
            {
                var subscription = new Subscription(channel, ackNackQueue);
                foreach (BasicDeliverEventArgs deliverEventArgs in subscription)
                {
                    var message = Encoding.UTF8.GetString(deliverEventArgs.Body);
                    Console.Out.WriteLine("message = {0}", message);

                    subscription.Ack(deliverEventArgs);
                }
            });
        }
Example #14
0
        /// <summary>
        /// Listen for incoming messages.
        /// </summary>
        /// <param name="token">
        /// The cancellation token to signal the worker to exit.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        private async Task ReceiveMessagesAsync(CancellationToken token)
        {
            using (var connection = this.connectionFactory.CreateConnection())
                using (var amqpModel = connection.CreateModel())
                {
                    amqpModel.ExchangeDeclare(this.ExchangeName, this.ExchangeType);
                    amqpModel.QueueDeclare(this.QueueName, true, false, false, null);
                    amqpModel.BasicQos(0, 1, false);

                    amqpModel.QueueBind(this.QueueName, this.ExchangeName, this.RoutingKey);

                    this.logger.LogInformation($"Waiting for messages on queue '{this.QueueName}' with routing key '{this.RoutingKey}'.");

                    var amqpSubscription = new Subscription(amqpModel, this.QueueName);
                    while (true)
                    {
                        var response = amqpSubscription.Next(SubscriptionNextTimeoutMilliseconds, out BasicDeliverEventArgs ea);
                        if (response == false)
                        {
                            if (amqpModel.IsClosed)
                            {
                                this.logger.LogWarning($"AMQP channel {amqpModel.ChannelNumber} is closed.");
                                return;
                            }

                            continue;
                        }

                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        this.logger.LogDebug($"RECEIVE: {ea.RoutingKey}: {message}");

                        var success = this.eventHandler.HandleMessage(message);
                        if (success)
                        {
                            amqpSubscription.Ack(ea);
                        }

                        ////await task;
                        ////var success = task.IsCompleted;
                        ////if (success)
                        ////{
                        ////    amqpModel.BasicAck(ea.DeliveryTag, false);
                        ////}

                        await Task.Delay(10, token);
                    }
                }
            // ReSharper disable once FunctionNeverReturns
        }
Example #15
0
        private static void RabbitListener()
        {
            IModel model        = GetRabbitChannel(exchangeName, queueName, routingKey);
            var    subscription = new Subscription(model, queueName, false);

            while (true)
            {
                BasicDeliverEventArgs basicDeliveryEventArgs = subscription.Next();
                string messageContent = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body);
                //messagesTextBox.Invoke((MethodInvoker)delegate { messagesTextBox.Text += messageContent + "\r\n"; });
                Console.WriteLine(messageContent);
                subscription.Ack(basicDeliveryEventArgs);
            }
        }
        /// <summary>
        ///
        /// </summary>
        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);
            }
        }
Example #17
0
        /// <summary>
        /// Get Messages In Queue
        /// </summary>
        /// <param name="state"></param>
        private async void GetMessagesInQueue(object state)
        {
            if (_running == true)
            {
                return;
            }

            _running = true;

            Console.WriteLine("Receiving Messages at " + DateTime.Now);

            Subscription subscription = _messageQueueConfigurations[0].GetSubscription();

            foreach (BasicDeliverEventArgs e in subscription)
            {
                string message = Encoding.UTF8.GetString(e.Body);

                MessageQueue messageQueue = JsonConvert.DeserializeObject <MessageQueue>(message);

                if (messageQueue.QueueName == string.Empty || messageQueue.QueueName == null)
                {
                    string originatingQueue = _messageQueueConfigurations[0].GetOriginatingQueueName();
                    if (originatingQueue != MessageQueueEndpoints.LoggingQueue)
                    {
                        messageQueue.QueueName = originatingQueue;
                    }
                }

                Console.WriteLine("Receiving Message id " + messageQueue.TransactionQueueId);

                ResponseModel <MessageQueue> responseMessage = await _messageProcessor.CommitInboundMessage(messageQueue, _connectionStrings);

                if (responseMessage.ReturnStatus == true)
                {
                    if (_appConfig.SendToLoggingQueue == true && messageQueue.TransactionCode != TransactionQueueTypes.Acknowledgement)
                    {
                        responseMessage = _messageQueueConfigurations[0].SendReceivedMessageToLoggingQueue(messageQueue, MessageQueueExchanges.Logging);
                    }

                    if (responseMessage.ReturnStatus == true)
                    {
                        Console.WriteLine($"Message Committed: {messageQueue.TransactionQueueId}");
                        subscription.Ack(e);
                    }

                    await _messageProcessor.ProcessMessages(_appConfig.InboundSemaphoreKey, _connectionStrings);
                }
            }
        }
Example #18
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);
                }
            }
        }
Example #19
0
        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");
        }
Example #20
0
 public void GetData()
 {
     try
     {
         var basicDeliveryEventArgs = SubscriptionForSecondQueue.Next();
         var messageContent         = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body);
         if (messageContent == _CommandStop)
         {
             SubscriptionForSecondQueue.Ack(basicDeliveryEventArgs);
             SubscriptionForSecondQueue.Close();
             FirstQueue.Model.Close();
             FirstQueue.Connection.Close();
             ServiceWork = false;
             return;
         }
         Console.WriteLine("Get data from queue #2: " + messageContent);
         SubscriptionForSecondQueue.Ack(basicDeliveryEventArgs);
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
         ServiceWork = false;
     }
 }
Example #21
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();
        }
Example #22
0
        private static void RabbitListener()
        {
            string hostName     = "localhost";
            string exchangeName = "backend-api";
            IModel channel      = GetRabbitChannel(hostName, exchangeName);
            var    subscription = new Subscription(channel, exchangeName, false);

            while (true)
            {
                BasicDeliverEventArgs basicDeliveryEventArgs = subscription.Next();
                string msg   = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body);
                string value = GetValueByKeyAndHostName(msg, hostName);
                Console.WriteLine(msg + " : " + value);
                subscription.Ack(basicDeliveryEventArgs);
            }
        }
Example #23
0
 private void Poll()
 {
     while (Enabled)
     {
         //Get next message
         var deliveryArgs = _subscription.Next();
         //Deserialize message
         var message   = Encoding.Default.GetString(deliveryArgs.Body);
         var dsMessage = JsonConvert.DeserializeObject <T>(message);
         OnReceiveMessage.Invoke(this, new RecieveMessageArgs <T> {
             Data = dsMessage
         });
         //Acknowledge message is processed
         _subscription.Ack(deliveryArgs);
     }
 }
Example #24
0
		private IMessage Receive (IModel model, int timeout, bool doAck)
		{
			string finalName = model.QueueDeclare (QRef.Queue, false);
			
			using (Subscription sub = new Subscription (model, finalName)) {
				BasicDeliverEventArgs result;
				if (sub.Next (timeout, out result)) {
					IMessage m = helper.ReadMessage (QRef, result);
					if (doAck)
						sub.Ack (result);
					return m;
				} else {
					throw new MonoMessagingException ("No Message Available");
				}
			}
		}
Example #25
0
        private void Poll()
        {
            while (Enabled)
            {
                //Get next message
                var deliveryArgs = _subscription.Next();
                //Deserialize message
                var message = Encoding.Default.GetString(deliveryArgs.Body);

                //Handle Message
                Console.WriteLine("Message Recieved - {0}", message);

                //Acknowledge message is processed
                _subscription.Ack(deliveryArgs);
            }
        }
        public void RabbitListener()
        {
            var model        = GetRabbitChannel(exchangeName, queueName, routingKey);
            var subscription = new Subscription(model, queueName, false);

            while (true)
            {
                BasicDeliverEventArgs basicDeliveryEventArgs = subscription.Next();
                string messageContent = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body);
                ThreadPool.QueueUserWorkItem(state =>
                {
                    MessageWork(messageContent);
                });

                subscription.Ack(basicDeliveryEventArgs);
            }
        }
Example #27
0
        public void ReceiveLoop()
        {
            Console.WriteLine("Waiting receiver starts on thread {0}", Thread.CurrentThread.ManagedThreadId);
            IsEnabled = true;

            while (IsEnabled)
            {
                var args    = mSubscription.Next();
                var message = Encoding.UTF8.GetString(args.Body);

                Console.WriteLine(" [x] Received {0} on subscription thread {1}", message, Thread.CurrentThread.ManagedThreadId);

                mSubscription.Ack(args);
            }

            Console.WriteLine("Waiting receiver exits.");
        }
Example #28
0
        private static async Task ReceiveMessagesAsync(SubscribeArguments options)
        {
            Console.WriteLine($"Connection to RabbitMQ at '{options.RabbitHostName}'");
            var factory = new ConnectionFactory {
                HostName = options.RabbitHostName
            };

            using (var connection = factory.CreateConnection())
                using (var amqpModel = connection.CreateModel())
                {
                    Console.WriteLine($"Declaring exchange '{options.ExchangeName}' (type={options.ExchangeType})");
                    amqpModel.ExchangeDeclare(options.ExchangeName, options.ExchangeType, durable: true);
                    var queueName = amqpModel.QueueDeclare().QueueName;

                    Console.WriteLine($"Waiting for messages on queue '{queueName}'.");

                    Console.WriteLine($"Binding to exchange using routing key'{options.RoutingKey}'");

                    amqpModel.QueueBind(queueName, options.ExchangeName, options.RoutingKey);
                    Subscription sub = new Subscription(amqpModel, queueName);

                    while (true)
                    {
                        var response = sub.Next(10, out BasicDeliverEventArgs ea);
                        if (response == false)
                        {
                            if (amqpModel.IsClosed)
                            {
                                Console.WriteLine("Channel is closed.");
                                return;
                            }

                            continue;
                        }

                        var body       = ea.Body;
                        var message    = Encoding.UTF8.GetString(body);
                        var routingKey = ea.RoutingKey;
                        Console.WriteLine($"Received {routingKey}: {message}");
                        sub.Ack(ea);

                        await Task.Delay(100);
                    }
                }
        }
Example #29
0
        /// <summary>
        ///		Poll for messages sent to queue.
        /// </summary>
        private void Poll()
        {
            while (Enabled)
            {
                //Get next message
                var deliveryArgs = _subscription.Next();
                //Deserialize message
                var messageString = Encoding.Default.GetString(deliveryArgs.Body);
                var settings      = new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.Auto
                };
                var receivedMessage = JsonConvert.DeserializeObject(messageString, settings);

                switch (receivedMessage)
                {
                case ClientMessage <ChatMessageModel> chatMessageDto:
                {
                    var chatMessage = Mapper.Map <ChatMessage>(chatMessageDto.Model);
                    // send chat message to view model
                    Messenger.Default.Send(new NotificationMessage <ChatMessage>(chatMessage, chatMessageDto.OperationType.ToString()), chatMessage.ChatRoomId);
                    break;
                }

                case ClientMessage <ChatRoomModel> chatRoomDto:
                {
                    var chatRoom = Mapper.Map <ChatRoom>(chatRoomDto.Model);
                    Messenger.Default.Send(new NotificationMessage <ChatRoom>(chatRoom, chatRoomDto.OperationType.ToString()));
                    break;
                }

                case ClientMessage <UserRoomModel> userDto:
                {
                    var user = Mapper.Map <User>(userDto.Model.User);
                    Messenger.Default.Send(new NotificationMessage <User>(user, userDto.OperationType.ToString()), userDto.Model.ChatRoom.Id);
                    break;
                }

                default:
                    throw new NotSupportedException("Unsupported message type sent to handler.");
                }

                // acknowledge message is processed
                _subscription.Ack(deliveryArgs);
            }
        }
        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(exchange: ExchangeName, type: "topic");
                    channel.QueueDeclare(queue: PurchaseOrderQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
                    channel.QueueBind(queue: PurchaseOrderQueueName, exchange: ExchangeName, routingKey: "payment.purchaseorder");

                    //the basic Qos with a prefix count of one.
                    //This means a consumer will reserve one message after queue to process at a time
                    //If any of those messages are not acknowledged when they are finished processing, then they will
                    //be put back onto the queue ready for another consumer to process them
                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
                    //channel.BasicQos(prefetchSize: 0, prefetchCount: 10, global: false);

                    //Subscription is a high level abstraction that has a more natural iterator feel to it.
                    //To use it we simply create a new instance and supply the channel
                    //and the queue which we want to get the messages from.
                    //noAck: false => consumer will acknowledge when it finishes processing
                    Subscription subscription = new Subscription(model: channel, queueName: PurchaseOrderQueueName, noAck: false);

                    while (true) //run an infinite loop to listen to messages in the queue
                    {
                        //we enter a while called next and the subscriptions get the next message
                        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);

                        // Once we have finished with the message,we call the ACK method and the subscription
                        // to acknowledge the message
                        subscription.Ack(deliveryArguments);
                    }
                }
            }
        }
        public void ProcessMessages()
        {
            // RabbitMQ Server建立连接

            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    Console.WriteLine($"服务端启动成功,{DateTime.Now}。");
                    Console.WriteLine("监听 Topic <payment.purchaseorder> 队列");
                    Console.WriteLine("------------------------------------------");
                    Console.WriteLine();

                    channel.ExchangeDeclare(ExchangeName, "topic");

                    //声明队列以向其发送消息消息

                    channel.QueueDeclare(PurchaseOrderQueueName, true, false, false, null);
                    channel.QueueBind(PurchaseOrderQueueName, ExchangeName, "payment.*");

                    channel.BasicQos(0, 1, false);
                    Subscription subscription = new Subscription(channel, PurchaseOrderQueueName, false);

                    while (true)
                    {
                        BasicDeliverEventArgs deliveryArguments = subscription.Next();
                        var routingKey = deliveryArguments.RoutingKey;

                        if (routingKey == "payment.purchaseorder")
                        {
                            var message = (PurchaseOrder)deliveryArguments.Body.DeSerialize(typeof(PurchaseOrder));
                            Console.WriteLine("-- Purchase Order - Routing Key <{0}> : {1}, ¥{2}, {3}, {4}", routingKey, message.CompanyName, message.AmountToPay, message.PaymentDayTerms, message.PoNumber);
                        }
                        if (routingKey == "payment.cardpayment")
                        {
                            var message = (CardPayment)deliveryArguments.Body.DeSerialize(typeof(CardPayment));
                            Console.WriteLine("-- Purchase Card - Routing Key <{0}> : {1}, {2}, ${3}", routingKey, message.Name, message.CardNumber, message.Amount);
                        }

                        subscription.Ack(deliveryArguments);
                    }
                }
            }
        }