Hướng dẫn cách chạy AWS SQS Local với Python

Chào các bạn,

Bài viết này sẽ hướng dẫn các bạn cách chạy dịch vụ AWS SQS của Amazon trong môi trường local với docker container.

Bước 1: Mở đường link bên dưới, copy file docker-compose.yml vào folder làm việc của các bạn.

https://github.com/localstack/localstack

Nội dung của file docker-compose.yml tương tự như bên dưới.

version: "3.8"

services:
  localstack:
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack
    network_mode: bridge
    ports:
      - "4566:4566"
      - "4571:4571"
      - "${PORT_WEB_UI-8080}:${PORT_WEB_UI-8080}"
    environment:
      - SERVICES=${SERVICES- }
      - DEBUG=${DEBUG- }
      - DATA_DIR=${DATA_DIR- }
      - PORT_WEB_UI=${PORT_WEB_UI- }
      - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR- }
      - KINESIS_ERROR_PROBABILITY=${KINESIS_ERROR_PROBABILITY- }
      - DOCKER_HOST=unix:///var/run/docker.sock
      - HOST_TMP_FOLDER=${TMPDIR}
    volumes:
      - "${TMPDIR:-/tmp/localstack}:/tmp/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

Bước 2: Mở một terminal, trỏ tới folder làm việc và chạy docker container với lệnh docker-compose up

Docker chạy thành công sẽ trả về giá trị giống như bên dưới.

localstack_main | Starting mock Resource Groups API service on http port 4566 ...
localstack_main | Starting mock Support service on http port 4566 ...
localstack_main | Waiting for all LocalStack services to be ready
localstack_main | Waiting for all LocalStack services to be ready
localstack_main | Waiting for all LocalStack services to be ready
localstack_main | Waiting for all LocalStack services to be ready
localstack_main | Ready.
localstack_main | 2021-05-21T14:35:41:INFO:localstack.utils.analytics.profiler: Execution of "start_api_services" took 32817.64602661133ms

Bước 3: Mở một terminal khác và cài AWS CLI ở link sau:

https://aws.amazon.com/vi/cli/

Bước 4: Gõ lệnh aws configure để thiết lập key name, password, area (us-east-1) và output type. Vì là môi trường local nên bạn có thể thiết lập đơn giản như key name = temp, password = temp, area = us-east-1, output type = json giống như bên dưới.

AWS Access Key ID [****************temp]: temp
AWS Secret Access Key [****************temp]: temp
Default region name [us-east-1]: us-east-1
Default output format [json]: json

Bước 5: Tạo một queue mới có tên là mymessage-queue với câu lệnh aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name mymessage-queue

Kết quả trả về giống như bên dưới.

{
    "QueueUrl": "http://localhost:4566/000000000000/mymessage-queue"
}

Bước 6: Tạo thêm một queue thứ hai tên mysecond-queue với câu lệnh aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name mysecond-queue

Kết quả trả về sẽ là:

{
    "QueueUrl": "http://localhost:4566/000000000000/mysecond-queue"
}

Bước 7: Kiểm tra danh sách các queue bằng lệnh aws --endpoint-url=http://localhost:4566 sqs list-queues

Ta sẽ nhận được kết quả trả về là:

{
    "QueueUrls": [
        "http://localhost:4566/000000000000/mymessage-queue",
        "http://localhost:4566/000000000000/mysecond-queue"
    ]
}

Bước 8: Gửi tin nhắn tới queue thứ nhất mymessage-queue với nội dung 'This is a message to the first queue'

aws --endpoint-url=http://localhost:4566 sqs send-message --queue-url http://localhost:4566/000000000000/mymessage-queue --message-body 'This is a message to the first queue!'

Kết quả nhận về sẽ là:

{
    "MD5OfMessageBody": "0cd6dd8360f2c3e3c7ccec1273edc427",
    "MessageId": "3239b311-dd5d-c546-7ac9-d54842dacb9f"
}

Bước 9: Nhận tin nhắn từ queue thứ nhất mymessage-queue với câu lệnh:

aws --endpoint-url=http://localhost:4566 sqs receive-message --queue-url http://localhost:4566/000000000000/mymessage-queue

Kết quả nhận được sẽ là:

{
    "Messages": [
        {
            "MessageId": "3239b311-dd5d-c546-7ac9-d54842dacb9f",
            "ReceiptHandle": "cfpezpakmnofchhucvwarezeehtvwxwnxspbvhfagxbecoivngzpqtafahswhbgfatzypreklnaodxjgiyfvndossujnsxfofllmgvskvevncgkezeeqjrgiazkjsypjfignlwzgauzfchkhvasbjreenogxytmlynwlwwhrscmjstedijbznezjd",
            "MD5OfBody": "0cd6dd8360f2c3e3c7ccec1273edc427",
            "Body": "This is a message to the first queue!"
        }
    ]
}

Nếu một queue có nhiều message, chúng ta có thể lấy tất cả message với câu lệnh như bên dưới (giả sử trong trường hợp này tôi muốn lấy tối đa 10 message).

aws --endpoint-url=http://localhost:4566 sqs receive-message --queue-url http://localhost:4566/000000000000/mymessage-queue --attribute-names All --max-number-of-messages 10

Kết quả nhận được sẽ tương tự như bên dưới.

{
    "Messages": [
        {
            "MessageId": "3239b311-dd5d-c546-7ac9-d54842dacb9f",
            "ReceiptHandle": "dldfcfdkaubnbgyzusesberzkzklgkwbtdpyeqtimeyaurjuerdqfxdiswtlnmjlnkpnuotsnqqwazjtnnelgagbaoposggqvbkcrfxvgzflyadcgaakycjmpkughlvdgxiddxdarbaxykjlczragyztfgivmglqmtairmlyuuptswxetldtcqdje",
            "MD5OfBody": "0cd6dd8360f2c3e3c7ccec1273edc427",
            "Body": "This is a message to the first queue!",
            "Attributes": {
                "SenderId": "AIDAIT2UOQQY3AUEKVGXU",
                "SentTimestamp": "1621608081464",
                "ApproximateReceiveCount": "2",
                "ApproximateFirstReceiveTimestamp": "1621608135690"
            }
        }
    ]
}

Tiếp theo tôi sẽ hướng dẫn cho các bạn dùng thư viên boto3 để gửi tin nhắn tới queue và nhận tin nhắn từ queue bằng Python. Bạn cần cài boto3 bằng lệnh pip3 install boto3nếu chưa cài.

Đoạn code cho việc gửi tin nhắn lên queue sẽ như bên dưới.

import boto3

sqs = boto3.client('sqs', aws_access_key_id='temp', aws_secret_access_key='temp',endpoint_url = 'http://localhost:4566')

queue_url = 'http://localhost:4566/000000000000/mysecond-queue'

msg = input('Enter your message: ')

response = sqs.send_message(
    QueueUrl = queue_url,
    MessageBody = (
        msg
    ) 
)

print(response['MessageId'])

Đoạn code cho việc nhận tin nhắn từ queue như bên dưới.

import boto3
#Get the service resource
sqs = boto3.resource('sqs', aws_access_key_id='temp', aws_secret_access_key='temp',endpoint_url = 'http://localhost:4566')

queue_url = 'http://localhost:4566/000000000000/mysecond-queue'

#Get the queue
queue = sqs.get_queue_by_name(QueueName = 'mysecond-queue')

#Process message by print out body
for message in queue.receive_messages():
    print(message.body)

Tổng kết

Như vậy trong bài viết này, tôi đã hướng dẫn cho các bạn cách tạo queue với AWS SQS trong môi trường local, gửi tin nhắn tới queue và nhận tin nhắn từ queue, và cách sử dụng Python để gửi/nhận tin nhắn. Chúc các bạn thành công. Bạn có thể để lại feedback ở phần comment bên dưới nếu có điều gì cần thảo luận. Thank you.

Bài viết bạn có thể quan tâm

About Author

Chia sẻ bài viết

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top