ReceiveMessage() 공개 메소드

Retrieves one or more messages (up to 10), from the specified queue. Using the WaitTimeSeconds parameter enables long-poll support. For more information, see Amazon SQS Long Polling in the Amazon SQS Developer Guide.

Short poll is the default behavior where a weighted random set of machines is sampled on a ReceiveMessage call. Thus, only the messages on the sampled machines are returned. If the number of messages in the queue is small (fewer than 1,000), you most likely get fewer messages than you requested per ReceiveMessage call. If the number of messages in the queue is extremely small, you might not receive any messages in a particular ReceiveMessage response. If this happens, repeat the request.

For each message returned, the response includes the following:

  • The message body.

  • An MD5 digest of the message body. For information on MD5, see RFC1321.

  • The MessageId you received when you sent the message to the queue.

  • The receipt handle.

  • The message attributes.

  • An MD5 digest of the message attributes.

The receipt handle is the identifier you must provide when deleting the message. For more information, see Queue and Message Identifiers in the Amazon SQS Developer Guide.

You can provide the VisibilityTimeout parameter in your request. The parameter is applied to the messages that Amazon SQS returns in the response. If you don't include the parameter, the overall visibility timeout for the queue is used for the returned messages. For more information, see Visibility Timeout in the Amazon SQS Developer Guide.

A message that isn't deleted or a message whose visibility isn't extended before the visibility timeout expires counts as a failed receive. Depending on the configuration of the queue, the message might be sent to the dead letter queue.

In the future, new attributes might be added. If you write code that calls this action, we recommend that you structure your code so that it can handle new attributes gracefully.

/// The action that you requested would violate a limit. For example, ReceiveMessage /// returns this error if the maximum number of inflight messages is reached. AddPermission /// returns this error if the maximum number of permissions for the queue is reached. ///
public ReceiveMessage ( ReceiveMessageRequest request ) : ReceiveMessageResponse
request Amazon.SQS.Model.ReceiveMessageRequest Container for the necessary parameters to execute the ReceiveMessage service method.
리턴 Amazon.SQS.Model.ReceiveMessageResponse
        static void Main(string[] args)
        {
            // AWS: Get instance public address
            string myId = "localhost";
            try
            {
                myId = Encoding.ASCII.GetString(new WebClient().DownloadData("http://169.254.169.254/latest/meta-data/public-hostname"));
            }
            catch
            {
            }

            // AWS SQS Client
            var sqsClient = new AmazonSQSClient();

            while (true)
            {
                // Get the next message
                ReceiveMessageRequest request = new ReceiveMessageRequest()
                    .WithQueueUrl("https://queue.amazonaws.com/*****/codeCampDemo")
                    .WithMaxNumberOfMessages(1);
                var response = sqsClient.ReceiveMessage(request);

                foreach (var retrievedMessage in response.ReceiveMessageResult.Message)
                {
                    var messageJson = JsonValue.Parse(retrievedMessage.Body);

                    var message = messageJson["message"].ReadAs<string>();

                    Console.WriteLine(message);

                    message = "Echo: " + message;

                    string address = string.Format("http://{0}", messageJson["sender"].ReadAs<string>());
                    var connection = new HubConnection(address);
                    connection.Start().Wait();

                    IHubProxy pongHub = connection.CreateProxy("MvcWebRole1.Hubs.EchoHub");
                    pongHub.Invoke("DoUpdateMessage", message, myId).Wait();

                    //Process the message and then delete the message
                    DeleteMessageRequest deleteRequest = new DeleteMessageRequest()
                        .WithQueueUrl("https://queue.amazonaws.com/******/codeCampDemo")
                        .WithReceiptHandle(retrievedMessage.ReceiptHandle);
                    sqsClient.DeleteMessage(deleteRequest);
                }

                Thread.Sleep(1000);
            }
        }
예제 #2
0
        static void ReadFromQueue(AWSCredentials credentials)
        {
            AmazonSQSClient client = new AmazonSQSClient(credentials, RegionEndpoint.USEast1);

            string queueUrl = "https://sqs.us-east-1.amazonaws.com/025631894481/aws-talk";

            ReceiveMessageRequest request = new ReceiveMessageRequest(queueUrl);
            request.MaxNumberOfMessages = 1;
            ReceiveMessageResponse response = client.ReceiveMessage(request);

            foreach (var message in response.Messages)
            {
                // Do something with the message
            }
        }
예제 #3
0
    public static void SQSReceiveMessage()
    {
      #region SQSReceiveMessage
      var client = new AmazonSQSClient();

      var request = new ReceiveMessageRequest
      {
        AttributeNames = new List<string>() { "All" },
        MaxNumberOfMessages = 5,
        QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue",
        VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds,
        WaitTimeSeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds
      };

      var response = client.ReceiveMessage(request);

      if (response.Messages.Count > 0)
      {
        foreach (var message in response.Messages)
        {
          Console.WriteLine("For message ID '" + message.MessageId + "':");
          Console.WriteLine("  Body: " + message.Body);
          Console.WriteLine("  Receipt handle: " + message.ReceiptHandle);
          Console.WriteLine("  MD5 of body: " + message.MD5OfBody);
          Console.WriteLine("  MD5 of message attributes: " +
            message.MD5OfMessageAttributes);
          Console.WriteLine("  Attributes:");

          foreach (var attr in message.Attributes)
          {
            Console.WriteLine("    " + attr.Key + ": " + attr.Value);
          }
        }
      }
      else
      {
        Console.WriteLine("No messages received.");
      }
      #endregion

      Console.ReadLine();
    }
예제 #4
0
        public static string DequeueByQueueUrl(string queueUrl)
        {
            using (var client = new AmazonSQSClient(Settings.AccessKey, Settings.Secret))
            {
                var request = new ReceiveMessageRequest()
                {
                    QueueUrl = queueUrl
                };

                var response = client.ReceiveMessage(request).Messages.First();

                var body = response.Body;

                var deleteRequest = new DeleteMessageRequest
                {
                    QueueUrl = queueUrl,
                    ReceiptHandle = response.ReceiptHandle
                };

                client.DeleteMessage(deleteRequest);

                return body;
            }
        }
예제 #5
0
 public virtual List<Message> ReadMessages(AmazonSQSClient sqsClient, string queueUrl)
 {
     // Create the request
     var receiveMessageRequest = new ReceiveMessageRequest
     {
         QueueUrl = queueUrl,
         MaxNumberOfMessages = 10
     };
     // Submit the request and return the response
     ReceiveMessageResponse resp = sqsClient.ReceiveMessage(receiveMessageRequest);
     return resp.Messages;
 }
예제 #6
0
        /// <summary>
        /// Deletes all messages from the input queue
        /// </summary>
        public void Purge()
        {
            if (_inputQueueAddress == null) return;

            using (var client = new AmazonSQSClient(_accessKeyId, _secretAccessKey, RegionEndpoint.EUCentral1))
            {
                try
                {
                    var response = client.ReceiveMessage(new ReceiveMessageRequest(_queueUrl)
                                          {
                                              MaxNumberOfMessages = 10
                                          });

                    while (response.Messages.Any())
                    {
                        var deleteResponse = client.DeleteMessageBatch(_queueUrl, response.Messages
                        .Select(m => new DeleteMessageBatchRequestEntry(m.MessageId, m.ReceiptHandle))
                        .ToList());

                        if (!deleteResponse.Failed.Any())
                        {
                            response = client.ReceiveMessage(new ReceiveMessageRequest(_queueUrl)
                                                             {
                                                                 MaxNumberOfMessages = 10
                                                             });
                        }
                        else
                        {
                            throw new Exception(deleteResponse.HttpStatusCode.ToString());
                        }
                    }


                }
                catch (Exception ex)
                {

                    Console.WriteLine("error in purge: " + ex.Message);
                }

            }





        }
예제 #7
0
        public static void Main(string[] args)
        {
            IAmazonSQS sqs = new AmazonSQSClient(RegionEndpoint.USWest2);

            try
            {
                Console.WriteLine("===========================================");
                Console.WriteLine("Getting Started with Amazon SQS");
                Console.WriteLine("===========================================\n");                
                
                //Creating a queue
                Console.WriteLine("Create a queue called MyQueue.\n");
                CreateQueueRequest sqsRequest = new CreateQueueRequest();
                sqsRequest.QueueName = "MyQueue";
                CreateQueueResponse createQueueResponse = sqs.CreateQueue(sqsRequest);
                String myQueueUrl;
                myQueueUrl = createQueueResponse.QueueUrl;

                //Confirming the queue exists
                ListQueuesRequest listQueuesRequest = new ListQueuesRequest();
                ListQueuesResponse listQueuesResponse = sqs.ListQueues(listQueuesRequest);

                Console.WriteLine("Printing list of Amazon SQS queues.\n");
                foreach (String queueUrl in listQueuesResponse.QueueUrls)
                {
                    Console.WriteLine("  QueueUrl: {0}", queueUrl);
                }
                Console.WriteLine();

                //Sending a message
                Console.WriteLine("Sending a message to MyQueue.\n");
                SendMessageRequest sendMessageRequest = new SendMessageRequest();
                sendMessageRequest.QueueUrl = myQueueUrl; //URL from initial queue creation
                sendMessageRequest.MessageBody = "This is my message text.";
                sqs.SendMessage(sendMessageRequest);
                
                //Receiving a message
                ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
                receiveMessageRequest.QueueUrl = myQueueUrl;
                ReceiveMessageResponse receiveMessageResponse = sqs.ReceiveMessage(receiveMessageRequest);

                Console.WriteLine("Printing received message.\n");
                foreach (Message message in receiveMessageResponse.Messages)
                {
                    Console.WriteLine("  Message");
                    Console.WriteLine("    MessageId: {0}", message.MessageId);
                    Console.WriteLine("    ReceiptHandle: {0}", message.ReceiptHandle);
                    Console.WriteLine("    MD5OfBody: {0}", message.MD5OfBody);
                    Console.WriteLine("    Body: {0}", message.Body);

                    foreach (KeyValuePair<string, string> entry in message.Attributes)
                    {
                        Console.WriteLine("  Attribute");
                        Console.WriteLine("    Name: {0}", entry.Key);
                        Console.WriteLine("    Value: {0}", entry.Value);
                    }
                }
                String messageRecieptHandle = receiveMessageResponse.Messages[0].ReceiptHandle;

                //Deleting a message
                Console.WriteLine("Deleting the message.\n");
                DeleteMessageRequest deleteRequest = new DeleteMessageRequest();
                deleteRequest.QueueUrl = myQueueUrl;
                deleteRequest.ReceiptHandle = messageRecieptHandle;
                sqs.DeleteMessage(deleteRequest);

            }
            catch (AmazonSQSException ex)
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
            }

            Console.WriteLine("Press Enter to continue...");
            Console.Read();
        }
예제 #8
0
        /// <summary>
        /// Task for Receiving messages from SQS
        /// </summary>
        /// <param name="state"></param>
        private void ReceiveTask(CancellationToken ct, int numberOfMessages)
        {
            try
            {
                // build the AWS SQS proxy client
                using (AmazonSQSClient client = new AmazonSQSClient(
                    this.AWSAccessKey, this.AWSSecretAccessKey,
                    new AmazonSQSConfig()
                        {
                            ServiceURL = this.AWSSQSServiceUrl,
                            MaxErrorRetry = 10
                        }))
                {
                    // build the request message
                    ReceiveMessageRequest request = new ReceiveMessageRequest();
                    request.AttributeName.Add("SentTimestamp");
                    request.MaxNumberOfMessages = 10;
                    request.QueueUrl = this.QueueUrl;
                    ReceiveMessageResponse response;
                    List<Message> messages = new List<Message>();
                    do
                    {
                        response = client.ReceiveMessage(request);
                        messages.AddRange(response.ReceiveMessageResult.Message);
                    }
                    while ((response.ReceiveMessageResult.Message.Count != 0) &
                           (messages.Count < numberOfMessages) &
                           (!ct.IsCancellationRequested));

                    // now add the Messages to the data store for the window thread
                    if (!ct.IsCancellationRequested)
                    {
                        lock (_setLock)
                        {
                            for (int i = 0; i < messages.Count; i++)
                            {
                                if (ct.IsCancellationRequested)
                                {
                                    break;
                                }
                                _set.Add(messages[i]);
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(this.GetType().Name,
                    ex.Message + "\n" + ex.StackTrace,
                    EventLogEntryType.Error);
            }
        }
예제 #9
0
        /// <summary>
        /// Deletes all messages from the input queue
        /// </summary>
        public void Purge()
        {
            if (Address == null) return;

            _log.Info("Purging {0} (by receiving all messages from the queue)", Address);

            try
            {
                using (var client = new AmazonSQSClient(_accessKeyId, _secretAccessKey, _amazonSqsConfig))
                {
                    var stopwatch = Stopwatch.StartNew();

                    while (true)
                    {
                        var response = client.ReceiveMessage(new ReceiveMessageRequest(_queueUrl)
                        {
                            MaxNumberOfMessages = 10
                        });

                        if (!response.Messages.Any()) break;

                        var deleteResponse = client.DeleteMessageBatch(_queueUrl, response.Messages
                            .Select(m => new DeleteMessageBatchRequestEntry(m.MessageId, m.ReceiptHandle))
                            .ToList());

                        if (deleteResponse.Failed.Any())
                        {
                            var errors = string.Join(Environment.NewLine,
                                deleteResponse.Failed.Select(f => $"{f.Message} ({f.Id})"));

                            throw new RebusApplicationException(
                                $@"Error {deleteResponse.HttpStatusCode} while purging: 
{errors}");
                        }
                    }

                    _log.Info($"Purging {Address} took {stopwatch.Elapsed.TotalSeconds:0.0} s");
                }
            }
            catch (AmazonSQSException exception) when (exception.StatusCode == HttpStatusCode.BadRequest)
            {
                if (exception.Message.Contains("queue does not exist")) return;

                throw;
            }
            catch (Exception exception)
            {
                throw new RebusApplicationException(exception, $"Error while purging {Address}");
            }
        }
예제 #10
0
        public void SetQueueConfigurationTests()
        {
            var filterRule = new FilterRule("Prefix", "test/");
            var s3Config = new AmazonS3Config();
            using (var s3Client = new AmazonS3Client(s3Config))
            using (var sqsClient = new AmazonSQSClient())
            {
                var createResponse = sqsClient.CreateQueue("events-test-" + DateTime.Now.Ticks);
                var bucketName = S3TestUtils.CreateBucket(s3Client);
                try
                {
                    var queueArn = sqsClient.AuthorizeS3ToSendMessage(createResponse.QueueUrl, bucketName);

                    PutBucketNotificationRequest putRequest = new PutBucketNotificationRequest
                    {
                        BucketName = bucketName,
                        QueueConfigurations = new List<QueueConfiguration>
                        {
                            new QueueConfiguration
                            {
                                Id = "the-queue-test",
                                Queue = queueArn,
                                Events = {EventType.ObjectCreatedPut},
                                Filter = new Filter
                                {
                                    S3KeyFilter = new S3KeyFilter
                                    {
                                        FilterRules = new List<FilterRule> 
                                        {
                                            filterRule
                                        }
                                    }
                                }
                            }
                        }
                    };

                    s3Client.PutBucketNotification(putRequest);

                    var getResponse = s3Client.GetBucketNotification(bucketName);

                    Assert.AreEqual(1, getResponse.QueueConfigurations.Count);
                    Assert.AreEqual(1, getResponse.QueueConfigurations[0].Events.Count);
                    Assert.AreEqual(EventType.ObjectCreatedPut, getResponse.QueueConfigurations[0].Events[0]);

                    Assert.IsNotNull(getResponse.QueueConfigurations[0].Filter);
                    Assert.IsNotNull(getResponse.QueueConfigurations[0].Filter.S3KeyFilter);
                    Assert.IsNotNull(getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules);
                    Assert.AreEqual(1, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules.Count);
                    Assert.AreEqual(filterRule.Name, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules[0].Name);
                    Assert.AreEqual(filterRule.Value, getResponse.QueueConfigurations[0].Filter.S3KeyFilter.FilterRules[0].Value);

                    Assert.AreEqual("the-queue-test", getResponse.QueueConfigurations[0].Id);
                    Assert.AreEqual(queueArn, getResponse.QueueConfigurations[0].Queue);

                    // Purge queue to remove test message sent configuration was setup.
                    sqsClient.PurgeQueue(createResponse.QueueUrl);
                    Thread.Sleep(TimeSpan.FromSeconds(1));

                    var putObjectRequest = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key = "test/data.txt",
                        ContentBody = "Important Data"
                    };

                    s3Client.PutObject(putObjectRequest);

                    string messageBody = null;
                    for (int i = 0; i < 5 && messageBody == null; i++)
                    {
                        var receiveResponse = sqsClient.ReceiveMessage(new ReceiveMessageRequest { QueueUrl = createResponse.QueueUrl, WaitTimeSeconds = 20 });
                        if (receiveResponse.Messages.Count != 0)
                        {
                            messageBody = receiveResponse.Messages[0].Body;
                        }
                    }


                    var evnt = S3EventNotification.ParseJson(messageBody);

                    Assert.AreEqual(1, evnt.Records.Count);
                    Assert.AreEqual(putObjectRequest.BucketName, evnt.Records[0].S3.Bucket.Name);
                    Assert.AreEqual(putObjectRequest.Key, evnt.Records[0].S3.Object.Key);
                    Assert.AreEqual(putObjectRequest.ContentBody.Length, evnt.Records[0].S3.Object.Size);
                }
                finally
                {
                    sqsClient.DeleteQueue(createResponse.QueueUrl);
                    AmazonS3Util.DeleteS3BucketWithObjects(s3Client, bucketName);
                }
            }
        }
예제 #11
0
        private void execute()
        {
            FolderVaultMapping mapping = Context.Mapping;
            ReceiveMessageRequest req = new ReceiveMessageRequest() { QueueUrl = mapping.NotificationQueueURL, MaxNumberOfMessages = 10 };
            List<QueueMessage> messages = new List<QueueMessage>();
            DeleteMessageBatchRequest deleter;
            ReceiveMessageResult result;
            List<Message> resultMessages;
            HashSet<string> exceptions = new HashSet<string>();
            long id = 0;

            using (AmazonSQSClient client = new AmazonSQSClient(mapping.AccessKey, mapping.SecretKey, mapping.Endpoint))
            {
                while (KeepRunning())
                {
                    try
                    {
                        messages.Clear();
                        result = client.ReceiveMessage(req).ReceiveMessageResult;
                        resultMessages = new List<Message>(result.Message);

                        for(int i = 0; i < resultMessages.Count; i++)
                        {
                            if (exceptions.Contains(resultMessages[i].MessageId))
                            {
                                resultMessages.RemoveAt(i);
                                i--;
                            }
                        }

                        if (resultMessages.Count > 0)
                        {
                            foreach (Message m in resultMessages)
                            {
                                try
                                {
                                    messages.Add(new QueueMessage(m.ReceiptHandle, m.MessageId, m.Body));
                                }
                                catch (InvalidDataException ex)
                                {
                                    Console.Error.WriteLine("Received an error parsing " + m.MessageId);
                                    Console.Error.WriteLine(ex);
                                    exceptions.Add(m.MessageId);
                                }
                            }

                            try
                            {
                                deleter = new DeleteMessageBatchRequest() { QueueUrl = mapping.NotificationQueueURL };

                                foreach (QueueMessage message in messages)
                                {
                                    try
                                    {
                                        Console.WriteLine("Handling a " + message.Action + " message with ID " + message.MessageId);
                                        if (message.Action == "ResultNotice" || handleMessage(message))
                                        {
                                            deleter.Entries.Add(new DeleteMessageBatchRequestEntry() { Id = "Delete" + (id++), ReceiptHandle = message.ReceiptHandle });
                                        }
                                        else
                                        {
                                            Console.WriteLine("    Unknown action");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.Error.WriteLine(ex);
                                        exceptions.Add(message.MessageId);
                                    }
                                }

                                if (deleter.Entries.Count > 0)
                                {
                                    client.DeleteMessageBatch(deleter);
                                }
                            }
                            catch(Exception ex)
                            {
                                Console.Error.WriteLine(ex);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < Settings.Default.PollInterval.TotalSeconds && KeepRunning(); i++)
                            {
                                Thread.Sleep(1000);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(ex);
                    }
                }
            }

            activePollers.Remove(this);
        }
예제 #12
0
    public static void SQSDeleteMessage()
    {
      #region SQSDeleteMessage
      var client = new AmazonSQSClient();

      var request = new ReceiveMessageRequest
      {
        AttributeNames = new List<string>() { "All" },
        MaxNumberOfMessages = 5,
        QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue",
        VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds,
        WaitTimeSeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds
      };

      var response = client.ReceiveMessage(request);

      if (response.Messages.Count > 0)
      {
        foreach (var message in response.Messages)
        {
          Console.Write("Message ID '" + message.MessageId + "' ");

          var delRequest = new DeleteMessageRequest
          {
            QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue",
            ReceiptHandle = message.ReceiptHandle
          };

          var delResponse = client.DeleteMessage(delRequest);
        }
      }
      else
      {
        Console.WriteLine("No messages to delete.");
      }
      #endregion

      Console.ReadLine();
    }
예제 #13
0
    public static void SQSChangeMessageVisibilityBatch()
    {
      #region SQSChangeMessageVisibilityBatch
      var client = new AmazonSQSClient();

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

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

      var msgResponse = client.ReceiveMessage(msgRequest);

      // Change visibility timeout for each message.
      if (msgResponse.Messages.Count > 0)
      {
        var entries = new List<ChangeMessageVisibilityBatchRequestEntry>();

        int numMessages = 0;

        foreach (var message in msgResponse.Messages)
        {
          numMessages += 1;

          var entry = new ChangeMessageVisibilityBatchRequestEntry
          {
            Id = "Entry" + numMessages.ToString(),
            ReceiptHandle = message.ReceiptHandle,
            VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds
          };

          entries.Add(entry);
        }

        var batRequest = new ChangeMessageVisibilityBatchRequest
        {
          Entries = entries,
          QueueUrl = url
        };

        var batResponse = client.ChangeMessageVisibilityBatch(batRequest);

        Console.WriteLine("Successes: " + batResponse.Successful.Count +
          ", Failures: " + batResponse.Failed.Count);

        if (batResponse.Successful.Count > 0)
        {
          foreach (var success in batResponse.Successful)
          {
            Console.WriteLine("  Success ID " + success.Id);
          }
        }

        if (batResponse.Failed.Count > 0)
        {
          foreach (var fail in batResponse.Failed)
          {
            Console.WriteLine("  Failure ID " + fail.Id + ":");
            Console.WriteLine("    Code: " + fail.Code);
            Console.WriteLine("    Message: " + fail.Message);
            Console.WriteLine("    Sender's fault?: " + fail.SenderFault);
          }
        }
      }
      #endregion

      Console.ReadLine();
    }
예제 #14
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
    }
예제 #15
0
    public static void SQSDeleteMessageBatch()
    {
      #region SQSDeleteMessageBatch
      var client = new AmazonSQSClient();

      var request = new ReceiveMessageRequest
      {
        AttributeNames = new List<string>() { "All" },
        MaxNumberOfMessages = 5,
        QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue",
        VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds,
        WaitTimeSeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds
      };

      var response = client.ReceiveMessage(request);
      var batchEntries = new List<DeleteMessageBatchRequestEntry>();

      if (response.Messages.Count > 0)
      {
        foreach (var message in response.Messages)
        {
          var batchEntry = new DeleteMessageBatchRequestEntry
          {
            Id = message.MessageId,
            ReceiptHandle = message.ReceiptHandle
          };

          batchEntries.Add(batchEntry);
        }

        var delRequest = new DeleteMessageBatchRequest
        {
          Entries = batchEntries,
          QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue"
        };

        var delResponse = client.DeleteMessageBatch(delRequest);

        if (delResponse.Failed.Count > 0)
        {
          Console.WriteLine("Failed deletions:");

          foreach (var failure in delResponse.Failed)
          {
            Console.WriteLine("  For ID '" + failure.Id + "': ");
            Console.WriteLine("    Code = " + failure.Code);
            Console.WriteLine("    Message = " + failure.Message);
            Console.WriteLine("    Sender's fault? = " + failure.SenderFault);
          }
        }

        if (delResponse.Successful.Count > 0)
        {
          Console.WriteLine("Successful deletions:");

          foreach (var success in delResponse.Successful)
          {
            Console.WriteLine("  ID '" + success.Id + "'");
          }
        }
      }
      else
      {
        Console.WriteLine("No messages to delete.");
      }
      #endregion

      Console.ReadLine();
    }
예제 #16
0
        public void MessageDeleted()
        {
            AddConfigValue("SQSWindow", "0.00:00:15");

            int visibilityTimeout = -1;
            // change the visibility timeout of the queue
            using (Amazon.SQS.AmazonSQSClient client = new AmazonSQSClient(
                ConfigurationManager.AppSettings["AWSAccessKey"],
                ConfigurationManager.AppSettings["AWSSecretAccessKey"],
                new AmazonSQSConfig()))
            {
                // store the visibilitytimeout so we can reset it
                GetQueueAttributesRequest getRequest = new GetQueueAttributesRequest();
                getRequest.QueueUrl = ConfigurationManager.AppSettings["QueueUrl"];
                getRequest.AttributeName.Add("VisibilityTimeout");
                GetQueueAttributesResponse response = client.GetQueueAttributes(getRequest);
                visibilityTimeout = response.GetQueueAttributesResult.VisibilityTimeout;

                // set it to 1 second
                SetQueueAttributesRequest setRequest = new SetQueueAttributesRequest();
                setRequest.QueueUrl = ConfigurationManager.AppSettings["QueueUrl"];
                setRequest.Attribute.Add(new Amazon.SQS.Model.Attribute() { Name = "VisibilityTimeout", Value = "1" });
                client.SetQueueAttributes(setRequest);

                String[] messageIds = new String[] { QueueMessage() };
                MockSQSService service = new MockSQSService();
                service.Start();
                PollForMessages(messageIds, service);

                ReceiveMessageRequest receiveRequest = new ReceiveMessageRequest();
                receiveRequest.QueueUrl = ConfigurationManager.AppSettings["QueueUrl"];
                ReceiveMessageResponse receiveResponse = client.ReceiveMessage(receiveRequest);

                Assert.AreEqual(0, receiveResponse.ReceiveMessageResult.Message.Where((m) => m.MessageId == messageIds[0]).Count());

                // set the visibility timeout back
                setRequest = new SetQueueAttributesRequest();
                setRequest.QueueUrl = ConfigurationManager.AppSettings["QueueUrl"];
                setRequest.Attribute.Add(new Amazon.SQS.Model.Attribute() { Name = "VisibilityTimeout", Value = visibilityTimeout.ToString() });
                client.SetQueueAttributes(setRequest);

                RemoveConfigValue("SQSWindow");
            }
        }