이 글에서는 Node.js 환경에서 SDK를 이용해 간단한 메시징 애플리케이션을 만들 것입니다. AWS Docs의 AWS SDK를 참고하여 진행합니다.
🎉 SDK란 Software Development kit로 특정 소프트웨어를 다루기 위한 키트다.
환경설정
프로젝트를 돌릴 루트 디렉터리에서 package.json을 만들어줍니다.
package.json
{
"name": "sdkfornode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@aws-sdk/client-sqs": "^3.100.0",
"aws-sdk": "^2.1147.0"
}
}
npm이 깔려있다면 package.json이 있는 위치에서 npm install을 통해 종속성을 설치할 수 있습니다. 종속성을 설치하면 디렉터리에 node_modules라는 폴더가 하나 만들어져 있을 것입니다.
다음으로는 내 소중한 리소스에 남이 함부로 접근하기 못하도록 인증 절차인 AWS credential을 설정해주어야 합니다. credential을 설정해주기 위한 위치는 C:\Users\user\. aws로 들어가서 credentials라는 파일을 열어보면 아래와 같은 텍스트가 있을 겁니다.
[default]
aws_access_key_id = 안녕하세요
aws_secret_access_key = 반갑습니다
이를 본인의 AWS 콘솔 홈 -> Security Credentials -> AccessKey -> Create New Access Key로 들어가 발급받은 access key와 secret key로 대체해주면 환경설정은 끝났습니다! ( 당연히 Node.js 등은 설치되어있어야 합니다. )
SQS queue 만들기
큐를 만드는 방법은 간단합니다. 아래와 같이 Amazon SQS -> Queues -> Create queue를 눌러 이름만 입력하고
Default 설정으로 큐를 만들어줍니다.
SQS Client 만들기
메시지 보내기와 메시지 받기 & 삭제하기에서도 사용할 SQSClient를 만들어줍니다. libs/sqsClient.js에 아래와 같은 코드를 적어줍니다.
import { SQSClient } from "@aws-sdk/client-sqs";
const REGION = "본인이 사용하고 있는 리전";
const sqsClient = new SQSClient({ region: REGION });
export { sqsClient };
큐로 메시지 보내기
코드를 짜기 전에 생성해둔 큐로 들어가 QueueURL을 복사해줍니다.
그리고 아래 코드를 넣고 자신의 큐 주소에 아까 복사한 URL을 넣어줍니다.
sendmsg.js
import { SendMessageCommand } from "@aws-sdk/client-sqs";
import { sqsClient } from "./libs/sqsClient.js";
const params = {
DelaySeconds: 10,
MessageAttributes: {
msg : {
DataType: "String",
StringValue: "The Whistler",
}
},
MessageBody:
"Hello world!",
QueueUrl: "자신의 큐 주소"
};
const run = async () => {
try {
const data = await sqsClient.send(new SendMessageCommand(params));
console.log("Sended MessageID:", data.MessageId);
return data;
} catch (err) {
console.log("Catched error : ", err);
}
};
run();
제대로 되었다면 node sendmsg.js로 실행시켜보면 아래와 같은 메시지가 나옵니다.
큐에서 메시지 풀링해오기
아래 코드로 위에서 메시지를 받고, 받은 메시지를 삭제할 수 있습니다.
getmsg.js
import { DeleteMessageCommand, ReceiveMessageCommand } from "@aws-sdk/client-sqs";
import { sqsClient } from "./libs/sqsClient.js";
const queueURL = "본인의 큐 URL";
const params = {
AttributeNames: ["SentTimestamp"],
QueueAttributeName: "ALL",
MessageAttributeNames: ["All"],
QueueUrl: queueURL,
WaitTimeSeconds: 3,
};
const delparms = {
QueueUrl: queueURL
}
const run = async () => {
try {
const data = await sqsClient.send(new ReceiveMessageCommand(params));
delparms.ReceiptHandle = data.Messages[0].ReceiptHandle
console.log(data.Messages[0].Body)
await sqsClient.send(new DeleteMessageCommand(delparms)) ;
return data;``
} catch (err) {
console.log("Error : " + err);
}
};
run();
"본인의 큐 URL" 부분에는 역시 위에서 한 것 같이 본인의 Queue URL 복사해 넣으시면 됩니다.
SQS Client를 활용한 기능들은 역시 docs를 보고 직접 해보는 것이 나을 것 같아 아래에 링크를 올려놨습니다.
docs에 가보면 제가 사용한 DeleteMessageCommand, ReceiveMessageCommand의 인자에 대한 설명도 잘 나와있으니까 한번 참고해보시면 좋을 것 같습니다.
AWS SDK for JavaScript v3
AWS SDK for JavaScript v3 The AWS SDK for JavaScript v3 is a rewrite of v2 with some great new features. As with version 2, it enables you to easily work with Amazon Web Services, but has a modular architecture with a separate package for each service. It
docs.aws.amazon.com
오류없이 작성 했다면 node getmsg.js로 실행시켰을 때 아래와 같은 결괏값을 받아옵니다!
AWS SQS 콘솔에서도 이와 같은 동작을 볼 수 있습니다.