-
-
Save wifecooky/f2c7b41090bfd2ad0fd3351a2ea5cadc to your computer and use it in GitHub Desktop.
[AWS][SQS] Shows how to use SQS to generate and receive messages in AWS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#in order to run the code above, install the python packages above: | |
#pip install ec2-metadata | |
#pip install boto3 | |
#!/usr/bin/python | |
import time | |
import boto3 | |
from ec2_metadata import ec2_metadata | |
#constants | |
QUEUE_NAME = 'MyQueueForProcessing' | |
REGION = 'us-east-1' | |
SQS_URL = 'https://sqs.us-east-1.amazonaws.com' | |
ACCOUNT_ID = '131111044735' | |
QUEUE_URL = SQS_URL + '/' + ACCOUNT_ID + '/' + QUEUE_NAME | |
#create the clients | |
sqs_client = boto3.client('sqs', REGION) | |
sqs = boto3.resource('sqs', REGION) | |
ec2_client = boto3.client('ec2', REGION) | |
#create the queue if it not exists | |
queue = sqs_client.create_queue( | |
QueueName=QUEUE_NAME, | |
Attributes={ | |
'VisibilityTimeout': '3000' | |
} | |
) | |
#send a message to the queue with one body and two custom attributes | |
response = sqs_client.send_message( | |
QueueUrl=QUEUE_URL, | |
MessageBody='Task 1', | |
MessageAttributes={ | |
'phantom': { | |
'StringValue': '1', | |
'DataType': 'String' | |
}, | |
'cosmic': { | |
'StringValue': '1', | |
'DataType': 'String' | |
} | |
} | |
) | |
time.sleep(5) #remove this line for production code! | |
#receive a message from the queue | |
queue1 = sqs.Queue(QUEUE_URL) | |
messages = queue1.receive_messages( | |
AttributeNames=[ | |
'All', | |
], | |
MessageAttributeNames=[ | |
'All', | |
] | |
) | |
MESSAGE_ID = messages[0].message_id | |
RECEIPT_HANDLE = messages[0].receipt_handle | |
#simulate processing: sleeps for a few seconds | |
print('PROCESSING...') | |
print('MESSAGE_ID..: ' + MESSAGE_ID) | |
print('RECEIPT.....: ' + RECEIPT_HANDLE) | |
for attribute in list(messages[0].message_attributes.keys()): | |
print(attribute, messages[0].message_attributes[attribute]['StringValue']) | |
time.sleep(5) #remove this line for production code! | |
print('END OF PROCESSING...') | |
#delete message from the queue: | |
response = sqs_client.delete_message( | |
QueueUrl=QUEUE_URL, | |
ReceiptHandle=RECEIPT_HANDLE | |
) | |
#optional, terminate the instance after the end of the processing | |
try: | |
instance_id = ec2_metadata.instance_id | |
ec2_client.terminate_instances( | |
InstanceIds=[ | |
instance_id, | |
] | |
) | |
except: | |
print("Not an EC2!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment