Amazon SQS Java SDK - cannot receive message attributes

John Simoes picture John Simoes · Aug 3, 2014 · Viewed 11k times · Source

After posting a message with an attribute to SQS with the following code before sending it (and checking in SQS console to see if everything is posted correctly)...

messageRequest.addMessageAttributesEntry(
        "attributeTest", 
        new MessageAttributeValue()
            .withDataType("String")
            .withStringValue("attributeTest 123"));

I cannot retrieve any of the message attributes in the message. All I see, as a result, is "0 attributes.". Reinspecting the message in Amazon SQS console, the message - and the attribute - are still there.

// Message was previously checked in SQS console and contains 
// an attribute named "attributeTest"

AmazonSQS sqs = ...
List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
for (Message : messages) 
{
    Map<String, MessageAttributeValue> attributes = message.getMessageAttributes();
    System.out.println("" + attributes.size() + " attributes.");
}

I am using Amazon SQS SDK v1.8 in Java 1.7 with Play Framework 2.2.3. At first I thought it could be the SQS version but tried upgrading to 1.8.7 with no avail.

The official documentation found here does not provide any sourcecode to read the attributes at all. Nor github searches, stack overflow. I've been trying for a few hours without any success.

Thanks for any help!

Answer

Ramesh Sen picture Ramesh Sen · Aug 15, 2014

You have to specify which message attributes you want in your request (or use "All" to get all message attributes). So in your case you could use either

List<Message> messages = sqs.receiveMessage(receiveMessageRequest.withMessageAttributeNames("attributeTest")).getMessages();

or

List<Message> messages = sqs.receiveMessage(receiveMessageRequest.withMessageAttributeNames("All")).getMessages();

If you want the standard attributes (ApproximateFirstReceiveTimestamp, ApproximateReceiveCount, SenderId, and SentTimestamp) along with your messages, use withAttributeNames("All"). You can find more detail in the Javadocs for ReceiveMessageRequest.