Ejemplo n.º 1
0
        private void OnTimeoutCallback(Message message)
        {
            var changeVisibilityRequest = new ChangeMessageVisibilityRequest
            {
                QueueUrl          = _queueUrl,
                VisibilityTimeout = 30,
                ReceiptHandle     = message.ReceiptHandle
            };

            _amazonSqsClient.ChangeMessageVisibilityAsync(changeVisibilityRequest, CancellationToken.None).RunSynchronously();
        }
        private IAsyncTask CreateRenewalTaskForMessage(Message message, string queueUrl, IAmazonSQS client)
        {
            return(m_amazonInternalSettings.AsyncTaskFactory.Create($"RenewPeekLock-{message.MessageId}", async() =>
            {
                m_log.Info("Renewing peek lock for message with ID {messageId}", message.MessageId);

                var request = new ChangeMessageVisibilityRequest(queueUrl, message.ReceiptHandle, (int)m_amazonInternalSettings.AmazonPeekLockDuration.PeekLockDuration.TotalSeconds);

                await client.ChangeMessageVisibilityAsync(request);
            }, intervalSeconds: (int)m_amazonInternalSettings.AmazonPeekLockDuration.PeekLockRenewalInterval.TotalSeconds, prettyInsignificant: true));
        }
Ejemplo n.º 3
0
        public bool ChangeVisibility(ChangeMessageVisibilityRequest request)
        {
            if (request == null)
            {
                return(false);
            }

            var response = SqsClient.ChangeMessageVisibility(request);

            return(response != null);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// add some time so that we can continue to work on this message
        /// </summary>
        /// <param name="recieptHandle"></param>
        /// <param name="extensionInSeconds"></param>
        /// <param name="highPriority"></param>
        /// <returns></returns>
        public bool ExtendMessageOwnerShip(string recieptHandle, int extensionInSeconds)
        {
            ChangeMessageVisibilityRequest changeMessageVisibilityRequest = new ChangeMessageVisibilityRequest
            {
                ReceiptHandle     = recieptHandle,
                VisibilityTimeout = extensionInSeconds,
                QueueUrl          = _QueueUrl
            };
            ChangeMessageVisibilityResponse ignoreThis = _AmazonSQSClient.ChangeMessageVisibilityAsync(changeMessageVisibilityRequest).Result;

            return(ignoreThis.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
        public IRequestContext Marshall(ChangeMessageVisibilityRequest input)
        {
            IRequestContext context = new RequestContext();

            context.AddParametr("Action", input.ActionName);
            context.AddParametr("Version", YandexMqConfig.DEFAULT_SERVICE_VERSION);

            context.AddParametr("QueueUrl", input.QueueUrl);
            context.AddParametr("ReceiptHandle", input.ReceiptHandle);
            context.AddParametr("VisibilityTimeout", input.VisibilityTimeout.ToString());

            return(context);
        }
Ejemplo n.º 6
0
        public async Task ChangeVisibilityTimeout(VQSqsQueueResponse receipt, TimeSpan visibilityTimeout)
        {
            var client = GetClient;

            var obj = new ChangeMessageVisibilityRequest
            {
                ReceiptHandle     = receipt.Receipt,
                QueueUrl          = await GetQueueUrl(client, receipt.QueueName),
                VisibilityTimeout = Convert.ToInt32(visibilityTimeout.TotalSeconds),
            };

            var response = await client.ChangeMessageVisibilityAsync(obj);
        }
Ejemplo n.º 7
0
        internal async Task ChangeMessageVisibilityAsync(
            string receiptHandle,
            TimeSpan timeout,
            CancellationToken cancellationToken)
        {
            var visibilityRequest = new ChangeMessageVisibilityRequest
            {
                QueueUrl          = _sqsQueue.Uri.ToString(),
                ReceiptHandle     = receiptHandle,
                VisibilityTimeout = (int)timeout.TotalSeconds,
            };

            await _sqsQueue.Client.ChangeMessageVisibilityAsync(visibilityRequest, cancellationToken).ConfigureAwait(false);
        }
Ejemplo n.º 8
0
        internal ChangeMessageVisibilityResponse ChangeMessageVisibility(ChangeMessageVisibilityRequest request)
        {
            var task = ChangeMessageVisibilityAsync(request);

            try
            {
                return(task.Result);
            }
            catch (AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return(null);
            }
        }
Ejemplo n.º 9
0
        private async Task ChangeVisibilityTimeOutAsyncTask(SQSEvent.SQSMessage message, ILambdaLogger contextLogger, int timeoutSeconds)
        {
            contextLogger.Log($" *** about to change visibility timeout  to {timeoutSeconds}  seconds***");

            var batRequest = new ChangeMessageVisibilityRequest
            {
                ReceiptHandle     = message.ReceiptHandle,
                VisibilityTimeout = timeoutSeconds,
                QueueUrl          = InputQueueUrl
            };

            var response = await this.SqSClient.ChangeMessageVisibilityAsync(batRequest);

            contextLogger.Log($" *** visibility timeout result status code is {response.HttpStatusCode} ***");
        }
Ejemplo n.º 10
0
        public override async Task RenewLockAsync(IQueueEntry <T> queueEntry)
        {
            _logger.Debug("Queue {0} renew lock item: {1}", _options.Name, queueEntry.Id);

            var entry   = ToQueueEntry(queueEntry);
            var request = new ChangeMessageVisibilityRequest {
                QueueUrl          = _queueUrl,
                VisibilityTimeout = (int)_options.WorkItemTimeout.TotalSeconds,
                ReceiptHandle     = entry.UnderlyingMessage.ReceiptHandle
            };

            await _client.Value.ChangeMessageVisibilityAsync(request).AnyContext();

            _logger.Trace("Renew lock done: {0}", queueEntry.Id);
        }
Ejemplo n.º 11
0
        IAsyncTask CreateRenewalTaskForMessage(Message message, IAmazonSQS client)
        {
            return(_asyncTaskFactory.Create(
                       $"RenewPeekLock-{message.MessageId}",
                       async() =>
            {
                _log.Info("Renewing peek lock for message with ID {messageId}", message.MessageId);

                var request = new ChangeMessageVisibilityRequest(_queueUrl, message.ReceiptHandle, (int)_peekLockDuration.TotalSeconds);

                await client.ChangeMessageVisibilityAsync(request).ConfigureAwait(false);
            },
                       intervalSeconds: (int)_peekLockRenewalInterval.TotalSeconds,
                       prettyInsignificant: true
                       ));
        }
Ejemplo n.º 12
0
        public Task <ChangeMessageVisibilityResponse> ChangeMessageVisibilityAsync(ChangeMessageVisibilityRequest request, CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var option = new InvokeOptions()
            {
                OriginalRequest      = request,
                RequestMarshaller    = new ChangeMessageVisibilityRequestMarshaller(),
                ResponseUnmarshaller = new ChangeMessageVisibilityResponseUnmarshaller()
            };

            return(InvokeAsync <ChangeMessageVisibilityResponse>(option, cancellationToken));
        }
Ejemplo n.º 13
0
        public override async Task RenewLockAsync(MessageEnvelope message, long lockTimeout)
        {
            CheckOpened(message.CorrelationId);

            // Extend the message visibility
            var envelope = (Message)message.Reference;

            if (envelope != null)
            {
                var request = new ChangeMessageVisibilityRequest()
                {
                    QueueUrl          = _queue,
                    ReceiptHandle     = envelope.ReceiptHandle,
                    VisibilityTimeout = (int)(lockTimeout / 1000)
                };
                await _client.ChangeMessageVisibilityAsync(request, _cancel.Token);

                _logger.Trace(message.CorrelationId, "Renewed lock for message {0} at {1}", message, this);
            }
        }
Ejemplo n.º 14
0
        public bool ChangeVisibility(ChangeMessageVisibilityRequest request)
        {
            if (request.ReceiptHandle.Equals(FakeBatchItemFailString, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            var item = GetInFlightItem(request.ReceiptHandle);

            if (request.VisibilityTimeout <= 0)
            {
                RequeueInFlightMessage(request.ReceiptHandle, force: true);
            }
            else
            {
                item.InFlightUntil = item.InFlightUntil += request.VisibilityTimeout;
            }

            return(true);
        }
Ejemplo n.º 15
0
        private async Task NoticeFailureAsync(SQSQueueSetting setting, Message message, int count = 0)
        {
            try
            {
                var changeRequest = new ChangeMessageVisibilityRequest(setting.QueueUrl, message.ReceiptHandle, 0);
                await this.SQSClient.ChangeMessageVisibilityAsync(changeRequest);

                this.logger.LogInformation($"Change visibility message (id:{message.MessageId})");
            }
            catch (Exception ex)
            {
                await this.NoticeFailureAsync(setting, message, count ++);

                if (count >= 10)
                {
                    this.logger.LogCritical(ex, $"Critical Error Can't change visibility message (id:{message.MessageId})");
                    throw;
                }
            }
        }
Ejemplo n.º 16
0
        public override async Task AbandonAsync(MessageEnvelope message)
        {
            CheckOpened(message.CorrelationId);

            // Make the message immediately visible
            var envelope = (Message)message.Reference;

            if (envelope != null)
            {
                var request = new ChangeMessageVisibilityRequest()
                {
                    QueueUrl          = _queue,
                    ReceiptHandle     = envelope.ReceiptHandle,
                    VisibilityTimeout = 0
                };
                await _client.ChangeMessageVisibilityAsync(request, _cancel.Token);

                message.Reference = null;
                _logger.Trace(message.CorrelationId, "Abandoned message {0} at {1}", message, this);
            }
        }
Ejemplo n.º 17
0
        public static void SQSChangeMessageVisibility()
        {
            #region SQSChangeMessageVisibility
            var client = new AmazonSQSClient();

            var url = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue";

            // Receive messages.
            var rcvRequest = new ReceiveMessageRequest
            {
                AttributeNames = new List <string>()
                {
                    "All"
                },
                QueueUrl = url
            };

            var rcvResponse = client.ReceiveMessage(rcvRequest);

            // Change visibility timeout for each message.
            if (rcvResponse.Messages.Count > 0)
            {
                foreach (var message in rcvResponse.Messages)
                {
                    var visRequest = new ChangeMessageVisibilityRequest
                    {
                        QueueUrl          = url,
                        ReceiptHandle     = message.ReceiptHandle,
                        VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds
                    };

                    client.ChangeMessageVisibility(visRequest);
                }
            }
            else
            {
                Console.WriteLine("No messages to change visibility for.");
            }
            #endregion
        }
Ejemplo n.º 18
0
        /**
         * Convert ChangeMessageVisibilityRequest to name value pairs
         */
        private IDictionary <String, String> ConvertChangeMessageVisibility(ChangeMessageVisibilityRequest request)
        {
            IDictionary <String, String> parameters = new Dictionary <String, String>();

            parameters.Add("Action", "ChangeMessageVisibility");
            if (request.IsSetQueueUrl())
            {
                parameters.Add("QueueUrl", request.QueueUrl);
            }
            if (request.IsSetReceiptHandle())
            {
                parameters.Add("ReceiptHandle", request.ReceiptHandle);
            }
            if (request.IsSetVisibilityTimeout())
            {
                parameters.Add("VisibilityTimeout", request.VisibilityTimeout + "");
            }
            List <Attribute> changeMessageVisibilityRequestAttributeList = request.Attribute;
            int changeMessageVisibilityRequestAttributeListIndex         = 1;

            foreach (Attribute changeMessageVisibilityRequestAttribute in changeMessageVisibilityRequestAttributeList)
            {
                if (changeMessageVisibilityRequestAttribute.IsSetName())
                {
                    parameters.Add("Attribute" + "." + changeMessageVisibilityRequestAttributeListIndex + "." + "Name", changeMessageVisibilityRequestAttribute.Name);
                }
                if (changeMessageVisibilityRequestAttribute.IsSetValue())
                {
                    parameters.Add("Attribute" + "." + changeMessageVisibilityRequestAttributeListIndex + "." + "Value", changeMessageVisibilityRequestAttribute.Value);
                }

                changeMessageVisibilityRequestAttributeListIndex++;
            }

            return(parameters);
        }
Ejemplo n.º 19
0
        /**
         * Convert ChangeMessageVisibilityRequest to name value pairs
         */
        private static IDictionary <string, string> ConvertChangeMessageVisibility(ChangeMessageVisibilityRequest request)
        {
            IDictionary <string, string> parameters = new Dictionary <string, string>();

            parameters["Action"] = "ChangeMessageVisibility";
            if (request.IsSetQueueUrl())
            {
                parameters["QueueUrl"] = request.QueueUrl;
            }
            if (request.IsSetReceiptHandle())
            {
                parameters["ReceiptHandle"] = request.ReceiptHandle;
            }
            if (request.IsSetVisibilityTimeout())
            {
                parameters["VisibilityTimeout"] = request.VisibilityTimeout.ToString();
            }
            List <Attribute> changeMessageVisibilityRequestAttributeList = request.Attribute;
            int changeMessageVisibilityRequestAttributeListIndex         = 1;

            foreach (Attribute changeMessageVisibilityRequestAttribute in changeMessageVisibilityRequestAttributeList)
            {
                if (changeMessageVisibilityRequestAttribute.IsSetName())
                {
                    parameters[String.Concat("Attribute", ".", changeMessageVisibilityRequestAttributeListIndex, ".", "Name")] = changeMessageVisibilityRequestAttribute.Name;
                }
                if (changeMessageVisibilityRequestAttribute.IsSetValue())
                {
                    parameters[String.Concat("Attribute", ".", changeMessageVisibilityRequestAttributeListIndex, ".", "Value")] = changeMessageVisibilityRequestAttribute.Value;
                }

                changeMessageVisibilityRequestAttributeListIndex++;
            }

            return(parameters);
        }
Ejemplo n.º 20
0
        public void ChangeMessageVisibility()
        {
            AmazonSQSClient client   = new AmazonSQSClient();
            string          queueUrl = "SQS_QUEUE_URL";

            var receiveMessageRequest = new ReceiveMessageRequest
            {
                AttributeNames        = { "SentTimestamp" },
                MaxNumberOfMessages   = 1,
                MessageAttributeNames = { "All" },
                QueueUrl = queueUrl
            };

            var response = client.ReceiveMessage(receiveMessageRequest);

            var changeMessageVisibilityRequest = new ChangeMessageVisibilityRequest
            {
                QueueUrl          = queueUrl,
                ReceiptHandle     = response.Messages[0].ReceiptHandle,
                VisibilityTimeout = 36000, // 10 hour timeout
            };

            client.ChangeMessageVisibility(changeMessageVisibilityRequest);
        }
Ejemplo n.º 21
0
        private async Task UpdateMessageVisibilityTimeout(SQSMessage message, string receiptHandle, Message typedMessage, Exception lastException)
        {
            if (TryGetApproxReceiveCount(message.Attributes, out int approxReceiveCount))
            {
                var visibilityTimeoutSeconds = (int)_messageBackoffStrategy.GetBackoffDuration(typedMessage, approxReceiveCount, lastException).TotalSeconds;

                try
                {
                    var visibilityRequest = new ChangeMessageVisibilityRequest
                    {
                        QueueUrl          = _queue.Url,
                        ReceiptHandle     = receiptHandle,
                        VisibilityTimeout = visibilityTimeoutSeconds
                    };

                    await _queue.Client.ChangeMessageVisibilityAsync(visibilityRequest);
                }
                catch (Exception ex)
                {
                    _log.LogError(0, ex, $"Failed to update message visibility timeout by {visibilityTimeoutSeconds} seconds");
                    _onError(ex, message);
                }
            }
        }
Ejemplo n.º 22
0
 public Task <ChangeMessageVisibilityResponse> ChangeMessageVisibilityAsync(
     ChangeMessageVisibilityRequest request,
     CancellationToken cancellationToken = new CancellationToken())
 {
     return(Task.FromResult(new ChangeMessageVisibilityResponse()));
 }
Ejemplo n.º 23
0
 public Task <ChangeMessageVisibilityResponse> ChangeMessageVisibilityAsync(ChangeMessageVisibilityRequest request, CancellationToken token = default(CancellationToken))
 {
     return(ChangeMessageVisibility(request).AsTaskResult());
 }
Ejemplo n.º 24
0
 public static ChangeMessageVisibilityResponse ChangeMessageVisibility(this IAmazonSQS client, ChangeMessageVisibilityRequest request)
 {
     return(client.ChangeMessageVisibilityAsync(request).GetResult());
 }
Ejemplo n.º 25
0
        public async Task <ChangeMessageVisibilityResponse> ChangeMessageVisibilityAsync(ChangeMessageVisibilityRequest request)
        {
            request.QueueName = this.QueueName;

            var marshaller   = new ChangeMessageVisibilityRequestMarshaller();
            var unmarshaller = ChangeMessageVisibilityResponseUnmarshaller.Instance;

            return(await _serviceClient.InvokeAsync <ChangeMessageVisibilityRequest, ChangeMessageVisibilityResponse>(request, marshaller, unmarshaller).ConfigureAwait(false));
        }
Ejemplo n.º 26
0
        public void Start()
        {
            #region Queue Releated Test Cases

            /* 1.1. Async create queue */
            var createQueueRequest = new CreateQueueRequest
            {
                QueueName  = _queueName,
                Attributes =
                {
                    DelaySeconds           =     10,
                    VisibilityTimeout      =     30,
                    MaximumMessageSize     =  40960,
                    MessageRetentionPeriod = 345600,
                    PollingWaitSeconds     = 15
                }
            };

            try
            {
                _client.BeginCreateQueue(createQueueRequest, CreateQueueCallback, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create queue failed, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 2.1 Async get queue attributes */
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                var getQueueAttributesRequest = new GetQueueAttributesRequest();
                nativeQueue.BeginGetAttributes(getQueueAttributesRequest, GetQueueAttributesCallback, nativeQueue);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Get queue attributes failed, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 3. Async list queue */
            try
            {
                do
                {
                    var listQueueRequest = new ListQueueRequest
                    {
                        QueueNamePrefix = _queueNamePrefix,
                        Marker          = _nextMarker,
                        MaxReturns      = 5
                    };

                    _client.BeginListQueue(listQueueRequest, ListQueueCallback, null);

                    _autoSetEvent.WaitOne();
                } while (_nextMarker != string.Empty);
            }
            catch (Exception ex)
            {
                Console.WriteLine("List queue failed, exception info: " + ex.Message);
            }

            /* 4. Async set queue attributes */
            var setQueueAttributesRequest = new SetQueueAttributesRequest
            {
                Attributes =
                {
                    DelaySeconds           =     0,
                    VisibilityTimeout      =    10,
                    MaximumMessageSize     = 10240,
                    PollingWaitSeconds     =    10,
                    MessageRetentionPeriod = 50000
                }
            };
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                nativeQueue.BeginSetAttributes(setQueueAttributesRequest, SetQueueAttributesCallback, nativeQueue);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Set queue attributes failed, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 2.2 Async get queue attributes again */
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                var getQueueAttributesRequest = new GetQueueAttributesRequest();
                nativeQueue.BeginGetAttributes(getQueueAttributesRequest, GetQueueAttributesCallback, nativeQueue);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Get queue attributes failed again, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 5.1. Async delete queue */
            var deleteQueueRequest = new DeleteQueueRequest(_queueName);
            deleteQueueRequest.AddHeader("Accept", "IE6");
            try
            {
                _client.BeginDeleteQueue(deleteQueueRequest, DeleteQueueCallback, _queueName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete queue failed, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 1.2. Async create queue again */
            try
            {
                _client.BeginCreateQueue(createQueueRequest, CreateQueueCallback, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create queue failed again, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            #endregion

            #region Messge Releated Test Cases

            /* 5. Async receive message */
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                for (int i = 0; i < _receiveTimes; i++)
                {
                    var receiveMessageRequest = new ReceiveMessageRequest();
                    nativeQueue.BeginReceiveMessage(receiveMessageRequest, ReceiveMessageCallback, nativeQueue);

                    _autoSetEvent.WaitOne();

                    Thread.Sleep(_receiveInterval);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Receive message failed, exception info: " + ex.Message);
            }

            /* 6. Async send message */
            try
            {
                var nativeQueue        = _client.GetNativeQueue(_queueName);
                var sendMessageRequest = new SendMessageRequest("阿里云计算");
                nativeQueue.BeginSendMessage(sendMessageRequest, SendMessageCallback, nativeQueue);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Send message failed, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 7. Async receive message */
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                for (int i = 0; i < _receiveTimes; i++)
                {
                    var receiveMessageRequest = new ReceiveMessageRequest();
                    nativeQueue.BeginReceiveMessage(receiveMessageRequest, ReceiveMessageCallback, nativeQueue);

                    _autoSetEvent.WaitOne();

                    Thread.Sleep(_receiveInterval);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Receive message failed, exception info: " + ex.Message);
            }

            /* 8. Async change message visibility */
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                var changeMessageVisibilityRequest = new ChangeMessageVisibilityRequest
                {
                    ReceiptHandle     = _receiptHandle,
                    VisibilityTimeout = 5
                };
                nativeQueue.BeginChangeMessageVisibility(changeMessageVisibilityRequest, ChangeMessageVisibilityCallback, nativeQueue);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Change message visibility failed, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 9. Async peek message */
            try
            {
                var nativeQueue        = _client.GetNativeQueue(_queueName);
                var peekMessageRequest = new PeekMessageRequest();
                for (uint i = 0; i < _receiveTimes; i++)
                {
                    nativeQueue.BeginPeekMessage(peekMessageRequest, PeekMessageCallback, nativeQueue);

                    _autoSetEvent.WaitOne();

                    Thread.Sleep(_receiveInterval);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Peek message failed, exception info: " + ex.Message);
            }

            /* 10. Async delete message */
            try
            {
                var nativeQueue            = _client.GetNativeQueue(_queueName);
                var receiveMessageResponse = nativeQueue.ReceiveMessage();
                _receiptHandle = receiveMessageResponse.Message.ReceiptHandle;
                var deleteMessageRequest = new DeleteMessageRequest(_receiptHandle);
                nativeQueue.BeginDeleteMessage(deleteMessageRequest, DeleteMessageCallback, nativeQueue);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Async BeginDeleteMessage failed, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            /* 11. Async batch send message */
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                List <SendMessageRequest> requests = new List <SendMessageRequest>();
                requests.Add(new SendMessageRequest("阿里云计算 Priority1", 0, 1));
                for (int i = 0; i < _batchSize; i++)
                {
                    requests.Add(new SendMessageRequest("阿里云计算" + i.ToString()));
                }
                BatchSendMessageRequest batchSendRequest = new BatchSendMessageRequest()
                {
                    Requests = requests
                };
                nativeQueue.BeginBatchSendMessage(batchSendRequest, BatchSendMessageCallback, nativeQueue);

                _autoSetEvent.WaitOne();
            }
            catch (Exception ex)
            {
                Console.WriteLine("BeginBatchSend message failed, exception info: " + ex.Message);
            }

            Thread.Sleep(12000);

            /* 12. Async batch peek message */
            try
            {
                var nativeQueue             = _client.GetNativeQueue(_queueName);
                var batchPeekMessageRequest = new BatchPeekMessageRequest(_batchSize + 2);
                Console.WriteLine(batchPeekMessageRequest.BatchSize.ToString());
                nativeQueue.BeginBatchPeekMessage(batchPeekMessageRequest, BatchPeekMessageCallback, nativeQueue);

                _autoSetEvent.WaitOne();
            }
            catch (Exception ex)
            {
                Console.WriteLine("BeginBatchPeek message failed, exception info: " + ex.Message);
            }

            /* 13. Async batch receive message */
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                BatchReceiveMessageRequest batchReceiveMessageRequest = new BatchReceiveMessageRequest(_batchSize + 1, 3);
                var batchReceiveMessageResponse = nativeQueue.BeginBatchReceiveMessage(batchReceiveMessageRequest, BatchReceiveMessageCallback, nativeQueue);
                _autoSetEvent.WaitOne();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Batch receive message failed, exception info: " + ex.Message);
            }

            /* 14. Async batch delete message */
            if (_batchReceiveMessageResponse != null && _batchReceiveMessageResponse.Messages.Count > 0)
            {
                try
                {
                    var           nativeQueue    = _client.GetNativeQueue(_queueName);
                    List <string> receiptHandles = new List <string>();
                    foreach (var message in _batchReceiveMessageResponse.Messages)
                    {
                        receiptHandles.Add(message.ReceiptHandle);
                    }
                    var batchDeleteMessageRequest = new BatchDeleteMessageRequest()
                    {
                        ReceiptHandles = receiptHandles
                    };
                    var batchDeleteMessageResponse = nativeQueue.BeginBatchDeleteMessage(batchDeleteMessageRequest, BatchDeleteMessageCallback, nativeQueue);
                    _autoSetEvent.WaitOne();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Batch delete message failed, exception info: " + ex.Message);
                }
            }

            #endregion

            #region Clean Generated Queue

            /* 5.2. Async delete queue again */
            try
            {
                _client.BeginDeleteQueue(deleteQueueRequest, DeleteQueueCallback, _queueName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete queue failed again, exception info: " + ex.Message);
            }

            _autoSetEvent.WaitOne();

            #endregion

            Console.ReadKey();
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Change Message Visibility
 /// </summary>
 /// <param name="request">Change Message Visibility  request</param>
 /// <returns>Change Message Visibility  Response from the service</returns>
 /// <remarks>
 /// The ChangeMessageVisibility action extends the read lock timeout of the specified message from the specified queue to the specified value.
 ///
 /// </remarks>
 public ChangeMessageVisibilityResponse ChangeMessageVisibility(ChangeMessageVisibilityRequest request)
 {
     return(Invoke <ChangeMessageVisibilityResponse>(ConvertChangeMessageVisibility(request)));
 }
Ejemplo n.º 28
0
 public Task <ChangeMessageVisibilityResponse> ChangeMessageVisibilityAsync(ChangeMessageVisibilityRequest request, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(amazonSqsToBeExtended.ChangeMessageVisibilityAsync(request, cancellationToken));
 }
Ejemplo n.º 29
0
 public ChangeMessageVisibilityResponse ChangeMessageVisibility(ChangeMessageVisibilityRequest request)
 {
     return(amazonSqsToBeExtended.ChangeMessageVisibility(request));
 }
Ejemplo n.º 30
0
        public async Task StartListeningAsync()
        {
            Logger.LogDebug("Starting SQS listener...");

            GetQueueDetailsFromAws();

            var request = new ReceiveMessageRequest
            {
                AttributeNames = new List <string> {
                    "All"
                },
                MaxNumberOfMessages = 5,
                QueueUrl            = _queueDetails.QueueUrl,
                VisibilityTimeout   = (int)TimeSpan.FromMinutes(2).TotalSeconds,
                WaitTimeSeconds     = (int)TimeSpan.FromSeconds(20).TotalSeconds
            };

            Started = true;

            while (!Shutdown)
            {
                Logger.LogDebug("Checking for new SQS messages...");
                var response = _sqsClient.ReceiveMessageAsync(request).Result;

                if (response.Messages.Count > 0)
                {
                    Logger.LogDebug($"Received {response.Messages.Count} messages from SQS");
                    foreach (var message in response.Messages)
                    {
                        Logger.LogDebug($"Processing message {message.MessageId}");
                        Logger.LogDebug($"Message contents: {message.Body.Replace("{", "{{").Replace("}", "}}")}");

                        T constructedMessage;
                        try
                        {
                            Logger.LogDebug($"Deserialising message body...");
                            constructedMessage = JsonConvert.DeserializeObject <T>(message.Body);
                            Logger.LogDebug($"Deserialised message {message.MessageId} successfully.");
                            Logger.LogDebug("Sanity check re-serialised:");
                            Logger.LogDebug(JsonConvert.SerializeObject(constructedMessage).Replace("{", "{{").Replace("}", "}}"));
                        }
                        catch (JsonReaderException ex)
                        {
                            Logger.LogError(ex, "Unknown message type.");

                            // Bad message, delete it from the queue.
                            Logger.LogError($"Deleting bad message from queue with ID {message.MessageId}");
                            Logger.LogError("Message body:");
                            Logger.LogError(message.Body);
                            var deleteMessageRequest = new DeleteMessageRequest(_queueDetails.QueueUrl, message.ReceiptHandle);
                            _sqsClient.DeleteMessageAsync(deleteMessageRequest).Wait();

                            continue;
                        }

                        try
                        {
                            await HandleMessageAsync(constructedMessage);

                            // Message handled, delete it from the queue.
                            var deleteMessageRequest = new DeleteMessageRequest(_queueDetails.QueueUrl, message.ReceiptHandle);
                            await _sqsClient.DeleteMessageAsync(deleteMessageRequest);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogDebug($"Processing of message failed.  Release message {message.MessageId} back to queue.");
                            Logger.LogDebug($"Error was: {ex.Message}");
                            Logger.LogDebug(ex.StackTrace);

                            var changeMessageRequest = new ChangeMessageVisibilityRequest(_queueDetails.QueueUrl, message.ReceiptHandle, 0);
                            await _sqsClient.ChangeMessageVisibilityAsync(changeMessageRequest);
                        }
                    }
                }
                else
                {
                    Logger.LogDebug("No sqs messages received.");
                }
            }

            Logger.LogDebug("Shutting down");
            Started = false;

            await Task.CompletedTask;
        }