Exemple #1
0
        public void Listening(TimeSpan timeout, CancellationToken cancellationToken)
        {
            Connect();

            var request = new ReceiveMessageRequest(_queueUrl)
            {
                WaitTimeSeconds     = 5,
                MaxNumberOfMessages = 1
            };

            while (true)
            {
                var response = _sqsClient !.ReceiveMessageAsync(request, cancellationToken).GetAwaiter().GetResult();

                if (response.Messages.Count == 1)
                {
                    var messageObj = JsonSerializer.Deserialize <SQSReceivedMessage>(response.Messages[0].Body);

                    var header = messageObj !.MessageAttributes.ToDictionary(x => x.Key, x => x.Value.Value);
                    var body   = messageObj.Message;

                    var message = new TransportMessage(header, body != null ? Encoding.UTF8.GetBytes(body) : null);

                    message.Headers.Add(Headers.Group, _groupId);

                    OnMessageReceived?.Invoke(response.Messages[0].ReceiptHandle, message);
                }
                else
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    cancellationToken.WaitHandle.WaitOne(timeout);
                }
            }
        }