/// <summary>
        /// Получить информацию о сообщениях, которые есть, но еще не отправлены указанному клиенту.
        /// </summary>
        /// <param name="clientId">Идентификатор клиента.</param>
        /// <param name="maxCount">Максимальное количество возвращаемых записей. Если равно 0, возвращается информация о всех имеющихся сообщениях.</param>
        /// <returns>Информация о сообщениях. Записи отсортированы в планируемом порядке отправки.</returns>
        public IEnumerable <ServiceBusMessageInfo> GetMessagesInfo(string clientId, int maxCount = 0)
        {
            string queueNamePrefix           = _namingManager.GetClientQueuePrefix(clientId);
            IEnumerable <Queue> queues       = _managementClient.GetQueuesAsync().Result;
            IEnumerable <Queue> clientQueues = queues.Where(x => x.Name.StartsWith(queueNamePrefix));

            List <ServiceBusMessageInfo> rmqMessagesInfo = new List <ServiceBusMessageInfo>();

            foreach (Queue clientQueue in clientQueues)
            {
                var messages = _managementClient.GetMessagesFromQueueAsync(clientQueue, new GetMessagesCriteria(clientQueue.Messages, Ackmodes.ack_requeue_true)).Result;
                foreach (var message in messages)
                {
                    ServiceBusMessageInfo msg = new ServiceBusMessageInfo
                    {
                        // TODO: Добавить заполнение других свойств.
                        MessageTypeID = _namingManager.GetMessageType(message.RoutingKey),
                    };

                    rmqMessagesInfo.Add(msg);
                }

                if (maxCount > 0 && rmqMessagesInfo.Count >= maxCount)
                {
                    rmqMessagesInfo = rmqMessagesInfo.Take(maxCount).ToList();
                    break;
                }
            }

            return(rmqMessagesInfo);
        }
Esempio n. 2
0
        public async Task Should_be_able_to_get_messages_from_a_queue()
        {
            var queue = await CreateTestQueue(testQueue).ConfigureAwait(false);

            var defaultExchange = new Exchange {
                Name = "amq.default", Vhost = vhostName
            };

            var publishInfo = new PublishInfo(
                new Dictionary <string, object>
            {
                { "app_id", "management-test" }
            },
                testQueue, "Hello World", "string");

            await managementClient.PublishAsync(defaultExchange, publishInfo).ConfigureAwait(false);

            foreach (var message in await managementClient.GetMessagesFromQueueAsync(queue, new GetMessagesCriteria(1, Ackmodes.ack_requeue_false)).ConfigureAwait(false))
            {
                Console.Out.WriteLine("message.Payload = {0}", message.Payload);
                foreach (var property in message.Properties)
                {
                    Console.Out.WriteLine("key: '{0}', value: '{1}'", property.Key, property.Value);
                }
            }
        }
        /// <summary>
        /// Returns messages from RabbitMQ.
        /// </summary>
        /// <param name="offset">Offset from start.</param>
        /// <param name="count">Count of messages.</param>
        /// <param name="clientId">Filter queues by client ID, empty string - do not filter.</param>
        /// <param name="messageTypeId">Filter queues by message type ID, empty string - do not filter.</param>
        /// <returns>Messages from RabbitMQ.</returns>
        public ServiceBusMessage[] GetMessages(int offset, int count, string clientId, string messageTypeId)
        {
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }

            if (count < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            int skipped    = 0;
            var sbMessages = new List <ServiceBusMessage>();

            IEnumerable <RabbitMQQueue> queues = FilterQueues(_managementClient.GetQueuesAsync().Result, clientId, messageTypeId);

            foreach (var queue in queues)
            {
                skipped += queue.Messages;
                if (skipped > offset)
                {
                    string _clientId;
                    string _messageTypeId;
                    _namingManager.ParseQueueName(queue.Name, out _clientId, out _messageTypeId);
                    var client = new Client()
                    {
                        ID = _clientId
                    };
                    var messageType = new MessageType()
                    {
                        ID = _messageTypeId
                    };

                    int skipInQueue         = offset > 0 ? queue.Messages - (skipped - offset) : offset;
                    int getFromQueue        = Math.Min(queue.Messages, count + skipInQueue - sbMessages.Count);
                    var getMessagesCriteria = new GetMessagesCriteria(getFromQueue, Ackmodes.ack_requeue_true);

                    IEnumerable <RabbitMQMessage> rmqMessages = _managementClient.GetMessagesFromQueueAsync(queue, getMessagesCriteria).Result.Skip(skipInQueue);
                    foreach (var rmqMessage in rmqMessages)
                    {
                        ServiceBusMessage sbMessage = _messageConverter.ConvertFromMqFormat(Convert.FromBase64String(rmqMessage.Payload), null);
                        sbMessage.Recipient   = client;
                        sbMessage.MessageType = messageType;
                        sbMessages.Add(sbMessage);
                    }

                    if (sbMessages.Count == count)
                    {
                        break;
                    }
                }
            }

            return(sbMessages.ToArray());
        }
        /// <summary>
        ///     Get messages from a queue.
        ///     Please note that the publish / get paths in the HTTP API are intended for
        ///     injecting test messages, diagnostics etc - they do not implement reliable
        ///     delivery and so should be treated as a sysadmin's tool rather than a
        ///     general API for messaging.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="queue">The queue to retrieve from</param>
        /// <param name="criteria">The criteria for the retrieve</param>
        /// <param name="cancellationToken"></param>
        /// <returns>Messages</returns>
        public static IReadOnlyList <Message> GetMessagesFromQueue(
            [NotNull] this IManagementClient source,
            [NotNull] Queue queue,
            GetMessagesCriteria criteria,
            CancellationToken cancellationToken = default
            )
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            return(source.GetMessagesFromQueueAsync(queue, criteria, cancellationToken)
                   .GetAwaiter()
                   .GetResult());
        }