Amazon MQ(RabbitMQ)를 사용하는 간단한 이벤트 기반 앱
15685 단어 rabbitmqmicroservicesawseventdriven
준비
샘플 앱에 Node.js를 사용하고 있으므로 Node.js 및 Yarn과 같은 도구가 필요합니다. 다음 게시물에서 C# 및 Go와 같은 다른 프로그래밍 언어를 사용한 또 다른 샘플을 제공하겠습니다. 이 Github Repository를 확인하여 둘러보실 수 있습니다.
bervProject / rabbitmq 데모
RabbitMQ 데모
RabbitMQ 데모
간단한 게시/구독 앱.
도구
Nodejs .
Yarn v1 .
준비
.env.sh.example를 .env.sh로 복사합니다. ,env.cmd.example를 .env.cmd로 복사합니다. .env.ps1.example를 .env.ps1로 복사합니다. .env 파일을 업데이트합니다. yarn --frozen-lockfile를 실행하여 종속성을 다운로드합니다. 소비자
node consumer.js . 게시자/발신자
node sender.js . 특허
MIT
View on GitHub
Amazon MQ에서 RabbitMQ 준비
AWS 콘솔을 통해 수동으로 RabbitMQ를 프로비저닝합니다.
검색 상자에서 Amazon MQ를 검색하고 Amazon MQ를 클릭합니다.

Get started 버튼을 클릭하세요.
RabbitMQ를 선택하고 Next를 클릭합니다.
테스트용으로만
Single-instance broker를 사용하고 프로덕션용으로 Cluster deployment를 사용할 수 있습니다. 그리고 Next 를 클릭합니다.
브로커 이름을 지정하고
mq.t3.micro 인스턴스를 선택합니다.
RabbitMQ 호스트의 사용자 이름과 암호를 설정합니다.

Additional setting를 엽니다. Public access 및 Use the default VPC and subnet(s) 를 선택했는지 확인하십시오. 생산용Public access은 피하십시오. Private access를 사용하고 프로덕션 용도로 VPC를 직접 설정해야 할 수 있습니다.
마지막으로
Next 을 클릭합니다. 구성을 검토하고 Create broker를 클릭합니다.
코딩할 시간입니다!
프로젝트를 초기화합니다.
yarn init를 사용하십시오. 프로젝트의 세부 정보를 입력합니다.
일부 종속성을 설치합니다.
yarn add amqplib - RabbitMQ에서 메시지를 보내거나 소비합니다. yarn add uuid - 메시지 ID 및 상관 관계 ID를 생성합니다. 발신자 코드
const amqp = require('amqplib');
const { v4: uuidv4 } = require('uuid');
// setup queue name
const queueName = 'test-queue';
/**
* Send message
*/
async function send() {
// connect to RabbitMQ
const connection = await amqp.connect(process.env.RABBITMQ_HOST || 'amqp://localhost');
// create a channel
const channel = await connection.createChannel();
// create/update a queue to make sure the queue is exist
await channel.assertQueue(queueName, {
durable: true,
});
// generate correlation id, basically correlation id used to know if the message is still related with another message
const correlationId = uuidv4();
// send 10 messages and generate message id for each messages
for (let i = 1; i <= 10; i++) {
const buff = Buffer.from(JSON.stringify({
test: `Hello World ${i}!!`
}), 'utf-8');
const result = channel.sendToQueue(queueName, buff, {
persistent: true,
messageId: uuidv4(),
correlationId: correlationId,
});
console.log(result);
}
// close the channel
await channel.close();
// close the connection
await connection.close();
}
send();
소비자 코드
const amqp = require('amqplib');
// setup queue name
const queueName = 'test-queue';
/**
* consume the message
*/
async function consume() {
// setup connection to RabbitMQ
const connection = await amqp.connect(process.env.RABBITMQ_HOST || 'amqp://localhost');
// setup channel
const channel = await connection.createChannel();
// make sure the queue created
await channel.assertQueue(queueName, {
durable: true,
});
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queueName);
// setup consume
channel.consume(queueName, function (message) {
// just print the message in the console
console.log("[%s] Received with id (%s) message: %s", message.properties.correlationId, message.properties.messageId, message.content.toString());
// ack manually
channel.ack(message);
}, {
// we use ack manually
noAck: false,
});
}
consume();
코드 테스트
환경 변수를 설정합니다. 예제 스크립트를 사용하여 환경 변수를 설정할 수 있습니다. 예를 들면:
$env:RABBITMQ_HOST = 'amqps://<username>:<password>@<rabbitmq-endpoint>:<rabbitmqport>'
export RABBITMQ_HOST=amqps://<username>:<password>@<rabbitmq-endpoint>:<rabbitmqport>
발신자를 실행하십시오.
node sender.js를 사용하십시오. 이와 같은 콘솔을 얻을 수 있습니다.
소비자를 실행합니다.
node consumer.js를 사용하십시오. 이와 같은 콘솔을 얻을 수 있습니다.
축하해요
축하해요! 메시지를 보내고 받는 간단한 앱을 만들었습니다. 리소스를 다시 사용하지 않을 경우 리소스를 정리하는 것을 잊지 마십시오.
Reference
이 문제에 관하여(Amazon MQ(RabbitMQ)를 사용하는 간단한 이벤트 기반 앱), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/aws-builders/simple-event-driven-app-using-amazon-mq-rabbitmq-22b0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)