자바스크립트를 이용한 Google Cloud Pub/Sub와의 통합 개발 방법

Google Cloud Pub/Sub는 이벤트 기반 메시지 전달 서비스로, 안정적이고 확장 가능한 실시간 데이터 및 이벤트 스트리밍을 지원합니다. 여기에는 메시지 발행(Publish)과 구독(Subscribe) 기능이 포함되어 있어, 간편하게 메시지를 보내고 받을 수 있습니다. 이번 블로그 포스트에서는 자바스크립트를 이용하여 Google Cloud Pub/Sub와의 통합 개발 방법을 알아보겠습니다.

Google Cloud Pub/Sub 설정

우선, Google Cloud Console에서 프로젝트를 생성하고 Google Cloud Pub/Sub를 활성화해야 합니다. 다음은 Google Cloud Pub/Sub를 설정하는 방법입니다:

  1. Google Cloud Console에 로그인합니다: https://console.cloud.google.com.
  2. 프로젝트를 선택하고 “Google Cloud Pub/Sub”을 검색하여 해당 서비스 페이지로 이동합니다.
  3. “활성화” 버튼을 클릭하여 Google Cloud Pub/Sub을 활성화합니다.
  4. 필요한 인증 및 권한 설정을 완료합니다.

이제 Google Cloud Pub/Sub를 사용할 준비가 끝났습니다. 이제는 자바스크립트를 사용하여 Google Cloud Pub/Sub와 통합하는 방법에 대해 알아보겠습니다.

Node.js 환경에서 Google Cloud Pub/Sub 사용하기

  1. Node.js 프로젝트를 생성하고 Google Cloud Pub/Sub 클라이언트 라이브러리를 설치합니다.
npm install @google-cloud/pubsub
  1. 다음과 같이 Pub/Sub 클라이언트를 생성하고 토픽(Topic)과 구독(Subscription)을 생성 또는 가져옵니다.
const { PubSub } = require('@google-cloud/pubsub');

const pubSubClient = new PubSub();
const topicName = 'my-topic';
const subscriptionName = 'my-subscription';

async function createTopic() {
  const [topic] = await pubSubClient.createTopic(topicName);
  console.log(`Topic ${topic.name} created.`);
}

async function createSubscription() {
  const [subscription] = await pubSubClient
    .topic(topicName)
    .createSubscription(subscriptionName);

  console.log(`Subscription ${subscription.name} created.`);
}

// 토픽 및 구독 생성
createTopic().catch(console.error);
createSubscription().catch(console.error);
  1. 메시지를 발행하려면 메시지를 JSON 형식으로 인코딩하여 Pub/Sub 클라이언트의 publish 메서드를 사용합니다.
async function publishMessage(data) {
  const dataBuffer = Buffer.from(JSON.stringify(data));

  const messageId = await pubSubClient
    .topic(topicName)
    .publish(dataBuffer);

  console.log(`Message ${messageId} published.`);
}

// 메시지 발행
const payload = { message: 'Hello Pub/Sub!' };
publishMessage(payload).catch(console.error);
  1. 메시지를 구독하려면 Pub/Sub 클라이언트의 subscribe 메서드를 사용하고, 메시지 처리를 위한 콜백 함수를 정의합니다.
async function receiveMessage() {
  const subscription = pubSubClient.subscription(subscriptionName);

  function messageHandler(message) {
    console.log(`Received message: ${message.id}`);
    console.log(`Data: ${message.data}`);

    message.ack();
  }

  subscription.on('message', messageHandler);
}

// 메시지 구독
receiveMessage().catch(console.error);

위의 예시 코드에서는 Node.js 환경에서 Google Cloud Pub/Sub와의 통합을 구현하는 방법을 보여주고 있습니다. Google Cloud Pub/Sub를 사용하여 메시지를 발행하고 구독하는 과정에서 중요한 점은 Pub/Sub 클라이언트의 메서드를 적절하게 호출하고, 토픽과 구독을 관리하는 것입니다.

이제 자바스크립트를 이용하여 Google Cloud Pub/Sub와 통합하는 방법에 대해 간단히 알아보았습니다. Google Cloud Pub/Sub는 안정적이고 확장 가능한 메시지 전달 서비스로, 다양한 애플리케이션과 시스템 간의 실시간 데이터 통신에 유용합니다.

#GoogleCloud #PubSub #자바스크립트