Thursday, May 23, 2013

Number of messages in AWS SQS



1. Spring configuration

<bean id="amazonSQSClient" class="com.amazonaws.services.sqs.AmazonSQSClient">
<constructor-arg>
<bean class="com.amazonaws.auth.BasicAWSCredentials">
<constructor-arg value="${amazon.access.key}" />
<constructor-arg value="${amazon.access.secret}" />
</bean>
</constructor-arg>
</bean>

2. Write your java code as


@Autowired
AmazonSQSClient amazonSQSClient;

..


public int getNoOfMessagesInQueue() {
AmazonSQS sqs = amazonSQSClient;
sqs.setEndpoint(endPoint);
GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(sqsUrl);
Collection<String> attributeNames = new ArrayList<String>();
attributeNames.add("All");
getQueueAttributesRequest.setAttributeNames(attributeNames);
GetQueueAttributesResult queueAttributes = sqs.getQueueAttributes(getQueueAttributesRequest);
return Integer.parseInt(queueAttributes.getAttributes().get("ApproximateNumberOfMessages"));
}