In this article, we will see how to setup the Amazon Simple Queue Service through AWS console and how to consume the messages using AWS SDK. To setup Amazon SQS, follow the below steps.
Step 1: From the AWS console, select the “SQS”.
Step 2: Click on “Create New Queue” and provide the queue name.
Step 3: Click on the “Queue Actions” to send the message to the queue.
Step 4: Collect the “Queue URL” from the AWS Console.
Step 5: We will write a simple consumer application using AWS JAVA SDK.
import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; public class AWSSQSSampleConsumer { public static void main(String[] args) throws Exception { AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider("<Provide Credentials file path here>", "sample").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. ", e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usWest2 = Region.getRegion(Regions.US_WEST_2); sqs.setRegion(usWest2); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SQS"); System.out.println("===========================================\n"); try { String myQueueUrl = "<Provide the Queue URL here>"; // Receive messages System.out.println("Receiving messages from MyQueue.\n"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { System.out.println(" Message"); System.out.println(" MessageId: " + message.getMessageId()); System.out.println(" Body: " + message.getBody()); } // Delete a message System.out.println("Deleting a message.\n"); String messageRecieptHandle = messages.get(0).getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle)); } catch (AmazonServiceException ase) { ase.printStackTrace(); } catch (AmazonClientException ace) { ace.printStackTrace(); } } }
Ride on Cloud Computing !!! and Happy Queuing !!!
Good and useful.