Simple Queue Service – Part 1

Tram Ho

Purpose

  • Call api to AWS Simple Queue Service(SQS) via sdk

Sample Code

Prepare

  • install aws sdk, run:

  • configure access-key and secret-key.

Create a session

  • create a session for reuse in other functions
  • profile used is default , to know profile is being configured, run on linux/mac

  • function to create a session

How to create a queue

  • use CreateQueue function in aws-sdk to create a queue for testing.
  • There are some important parameters to note:
    • queueName : the name of the queue you want to create
    • DelaySeconds : how long the message you want to keep before sending,
    • VisibilityTimeout : the time a message takes before it expires.
  • function create 1 queue

Get the URL of a queue

  • All apis require the url of the queue, so use GetQueueURL to query the url of the queue-name
  • function get url

Send message to queue

  • we will use SendMessage function from aws-sdk to send message to queue
  • Some important parameters to pay attention to while sending messages:
    • QueueUrl : the url of the queue that wants to send the message.
    • MessageBody: body sent to the queue, can be json-string or string
  • function send message

Receive messages from queue

  • we will use ReceiveMessage function from aws-sdk to get message from queue
  • Some important parameters need to be noticed while receiving messages:
    • QueueUrl : the url of the queue that wants to receive the message.
    • MaxNumberOfMessages : total number of messages that can be received.
  • function receive message:

Delete messages in the queue

  • When receiving a message from the queue, the message is not automatically removed from the queue.
  • Other consumers can receive the message after the VisibilityTimeout has expired.
  • To ensure that there are no duplicate messages, it needs to be deleted.
  • we will use DeleteMessage function from aws-sdk to delete message from queue
  • need to provide ReceiptHandle in method component
  • function to delete messages:

Delete all messages in the queue

  • we will use PurgeQueue function from aws-sdk to delete all messages in queue
  • Some important paramters need to be noticed while deleting all messages:
  • function to delete all messages:

Ref

Share the news now

Source : Viblo