public DeleteMessageAsync ( |
||
request | Container for the necessary parameters to execute the DeleteMessage operation. | |
cancellationToken | System | /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// |
Результат | Task |
public async Task ConsumeAsync(int maxMessages = 5, CancellationToken token = default) { Console.WriteLine("\nConsuming messages:"); using (var client = new Amazon.SQS.AmazonSQSClient(accessKey, secretKey, region)) { var queueUrlResult = await client.GetQueueUrlAsync(queueName, token); var queueUrl = queueUrlResult.QueueUrl; while (true) { /// Console.WriteLine("Fetching messages:"); var req = new ReceiveMessageRequest(queueUrl); req.WaitTimeSeconds = 20; // long pooling req.MaxNumberOfMessages = maxMessages; var r = await client.ReceiveMessageAsync(req, token); if (r.Messages.Count > 0) { foreach (var m in r.Messages) { Console.WriteLine("[" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + "] [C] " + m.Body + " | " + m.MessageId); // ack await client.DeleteMessageAsync(queueUrl, m.ReceiptHandle); } } } } }
public void Acknowledge(Message message) { if(!message.Header.Bag.ContainsKey("ReceiptHandle")) return; var receiptHandle = message.Header.Bag["ReceiptHandle"].ToString(); try { using (var client = new AmazonSQSClient()) { client.DeleteMessageAsync(new DeleteMessageRequest(_queueUrl, receiptHandle)); _logger.InfoFormat("SqsMessageConsumer: Deleted the message {0} with receipt handle {1} on the queue {2}", message.Id, receiptHandle, _queueUrl); } } catch (Exception exception) { _logger.ErrorException("SqsMessageConsumer: Error during deleting the message {0} with receipt handle {1} on the queue {2}", exception, message.Id, receiptHandle, _queueUrl); throw; } }
/// <summary> /// Rejects the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="requeue">if set to <c>true</c> [requeue].</param> public void Reject(Message message, bool requeue) { if (!message.Header.Bag.ContainsKey("ReceiptHandle")) return; var receiptHandle = message.Header.Bag["ReceiptHandle"].ToString(); try { _logger.Value.InfoFormat("SqsMessageConsumer: Rejecting the message {0} with receipt handle {1} on the queue {2} with requeue paramter {3}", message.Id, receiptHandle, _queueUrl, requeue); using (var client = new AmazonSQSClient(_credentials)) { if (requeue) { client.ChangeMessageVisibilityAsync(new ChangeMessageVisibilityRequest(_queueUrl, receiptHandle, 0)).Wait(); } else { client.DeleteMessageAsync(_queueUrl, receiptHandle).Wait(); } } _logger.Value.InfoFormat("SqsMessageConsumer: Message {0} with receipt handle {1} on the queue {2} with requeue paramter {3} has been rejected", message.Id, receiptHandle, _queueUrl, requeue); } catch (Exception exception) { _logger.Value.ErrorException("SqsMessageConsumer: Error during rejecting the message {0} with receipt handle {1} on the queue {2}", exception, message.Id, receiptHandle, _queueUrl); throw; } }
/// <summary> /// The main entrypoint for the thread that listens to messages. /// </summary> private void AWSMessageListener() { // Used to eliminate over logging bool receivedMessage = true; while (!stopping) { try { var receiveMessageRequest = new SQS.Model.ReceiveMessageRequest() { WaitTimeSeconds = 10, QueueUrl = sqsQueueUrl }; if (receivedMessage) { Logger.LogTrace("Waiting for message from queue"); } receivedMessage = false; var messageResponse = AsyncTaskHelper.RunSync(() => sqsClient.ReceiveMessageAsync(receiveMessageRequest)); if (messageResponse.HttpStatusCode == HttpStatusCode.OK && messageResponse.Messages.Count > 0 && !stopping) { receivedMessage = true; Logger.LogDebug($"Received {messageResponse.Messages.Count} message(s)"); foreach (var messageResponseMessage in messageResponse.Messages) { try { ProcessMessage(messageResponseMessage); } finally { #if (!DONTDELETEMESSAGE) // Delete the message even in error since it will keep coming back // Perhaps a better action would be to put in a dead letter queue DeleteMessage(messageResponseMessage); #endif } } } } catch (Exception ex) { Logger.LogError("Error processing message: {0}", ex); } } // Process the received message void ProcessMessage(SQS.Model.Message messageResponseMessage) { Logger.LogTrace($"Received Message ({messageResponseMessage.MessageId}): {messageResponseMessage.Body}"); var snsMessage = SNS.Util.Message.ParseMessage(messageResponseMessage.Body); var feedEvent = JsonConvert.DeserializeObject <FeedEvent>(snsMessage.MessageText); Logger.LogInformation($"Feed: {feedEvent.Feed}, Event: {feedEvent.Event}, Package: {feedEvent.Package}, Version: {feedEvent.Version}"); Logger.LogTrace($"Package URL: {feedEvent.PackageUrl}"); var actionableActions = ApplicationSettings.Actions.Where(action => string.Equals(action.SourceFeed, feedEvent.Feed, StringComparison.InvariantCultureIgnoreCase) && action.Enabled); Package retrievedPackage = null; foreach (var actionableAction in actionableActions) { Logger.LogTrace($"Found Action ({actionableAction.Name}) for {feedEvent.Feed}"); if (feedEvent.Version.IsPrerelease() && !actionableAction.IncludePrerelease) { Logger.LogDebug($"{actionableAction.Name} is ignoring prelease package ({feedEvent.Package}.{feedEvent.Version})"); continue; } using (var scope = ServiceProvider.CreateScope()) { var action = ActionProcessor.CreateAction(scope, actionableAction); switch (feedEvent.Event) { case EventType.Added: if (retrievedPackage == null) { retrievedPackage = AsyncTaskHelper.RunSync(() => action.SourceRepository.FetchAsync(feedEvent.Package, feedEvent.Version)); } if (retrievedPackage == null) { Logger.LogWarning($"{feedEvent.Package}.{feedEvent.Version} not found in feed {feedEvent.Feed}. Ignoring."); } else { AsyncTaskHelper.RunSync(() => action.ProcessPackageAsync(retrievedPackage, PackageEvent.Added)); } break; case EventType.Deleted: case EventType.Purged: // We can't retrieve the package because it has been deleted var deletePackage = new Package { Id = feedEvent.Package, Version = feedEvent.Version }; AsyncTaskHelper.RunSync(() => action.ProcessPackageAsync(deletePackage, PackageEvent.Deleted)); break; } } } } #if (!DONTDELETEMESSAGE) // Delete the processed message from the queue void DeleteMessage(SQS.Model.Message messageResponseMessage) { var deleteMessageRequest = new SQS.Model.DeleteMessageRequest { QueueUrl = sqsQueueUrl, ReceiptHandle = messageResponseMessage.ReceiptHandle }; Logger.LogTrace($"Deleting Message: {messageResponseMessage.ReceiptHandle}"); var deleteMessageResponse = AsyncTaskHelper.RunSync(() => sqsClient.DeleteMessageAsync(deleteMessageRequest)); if (deleteMessageResponse.HttpStatusCode == HttpStatusCode.OK) { Logger.LogTrace($"Delete Message: {messageResponseMessage.ReceiptHandle}"); } else { Logger.LogWarning($"Unable to delete Message: {messageResponseMessage.ReceiptHandle}. Ignoring."); } } #endif }