public ReceiveMessageAsync ( |
||
request | Container for the necessary parameters to execute the ReceiveMessage operation. | |
cancellationToken | System | /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// |
리턴 | Task |
public async Task<Amazon.SQS.Model.Message> GetMessage(string queueName, int timeoutInMilliseconds, int numberOfCacheableMessages) { Amazon.SQS.Model.Message message = null; if (_queue.ContainsKey(queueName) && _queue[queueName].TryDequeue(out message)) return message; var request = new ReceiveMessageRequest(queueName) { MaxNumberOfMessages = numberOfCacheableMessages, WaitTimeSeconds = (int)TimeSpan.FromMilliseconds(timeoutInMilliseconds).TotalSeconds }; using (var client = new AmazonSQSClient(_credentials)) { var response = await client.ReceiveMessageAsync(request); if (response.HttpStatusCode != HttpStatusCode.OK) return message; if (response.ContentLength == 0) return message; if (!response.Messages.Any()) return message; AddToQueue(queueName, response.Messages); if(_queue.ContainsKey(queueName)) _queue[queueName].TryDequeue(out message); } return message; }
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); } } } } }
/// <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 }