Azure queues – updating messages

The default invisibility timeout of 30 seconds may not suffice on occasions. For those situations, you can change the timeout so that you get more time to do something with your message prior to deleting it.

void DeQueueMessagesWithTimeOut(std::chrono::seconds timeout)
{
  auto storage_account = cloud_storage_account::parse(
      U("UseDevelopmentStorage=true"));
  auto queue_client = storage_account.create_cloud_queue_client();
  auto queue = queue_client.get_queue_reference(
      U("sample"));
  bool created = queue.create_if_not_exists();

  queue.download_attributes();
  int count = queue.approximate_message_count();
  ucout << U("Approx count = ") << count << endl;

  queue_request_options options;
  operation_context op_context;
  auto messages = queue.get_messages(
      count, timeout, options, op_context);
  for (auto message : messages)
  {
    // process the message here
    queue.delete_message(message);
    ucout << message.content_as_string() << endl;
  }

  queue.download_attributes();
  count = queue.approximate_message_count();
  ucout << U("Approx count = ") << count << endl;
}

You can also update an existing message. The code snippet below shows how that can be done.

void UpdateQueueMessage()
{
  auto storage_account = cloud_storage_account::parse(
      U("UseDevelopmentStorage=true"));
  auto queue_client = storage_account.create_cloud_queue_client();
  auto queue = queue_client.get_queue_reference(
      U("sample"));
  bool created = queue.create_if_not_exists(); 

  auto message = queue.get_message();
  message.set_content(U("Updated content"));
  queue.update_message(
      message, std::chrono::seconds(0), true);
}

One thing to be aware of is that the position of the message in the queue is lost. The updated content goes back to the back of the queue. This shouldn’t matter though for most practical scenarios as the order of items in the queue is not expected to be depended on by consumers. This might be a little different to how you used queues in your programming classes, where it was a guaranteed FIFO structure. But remember, those queues did not allow in-place edits either.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s