Pub/Sub 트리거


Google Cloud의 Pub/Sub는 필요에 따라 자동으로 확장되는 글로벌 분산형 메시지 버스입니다. functions.pubsub를 사용하여 Pub/Sub 이벤트를 처리하는 함수를 만들 수 있습니다.

Pub/Sub 함수 트리거

새 Pub/Sub 메시지가 특정 주제로 전송될 때마다 함수를 트리거할 수 있습니다. 함수를 트리거할 Pub/Sub 주제 이름을 지정하고 onPublish() 이벤트 핸들러 내에서 이벤트를 설정해야 합니다.

exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish((message) => {
  // ...
});

Pub/Sub 메시지 페이로드에 액세스{:#access-pub/sub}

Pub/Sub 메시지의 페이로드는 함수에 반환된 Message 객체에서 액세스할 수 있습니다. Pub/Sub 메시지 본문에 JSON이 포함된 경우 Cloud Functions용 Firebase SDK의 도우미 속성으로 메시지를 디코딩할 수 있습니다. 예를 들어 다음은 간단한 JSON 페이로드와 함께 게시된 메시지입니다.

gcloud pubsub topics publish topic-name --message '{"name":"Xenia"}'

json 속성을 통해 다음과 같이 JSON 데이터 페이로드에 액세스할 수 있습니다.

  // Get the `name` attribute of the PubSub message JSON body.
  let name = null;
  try {
    name = message.json.name;
  } catch (e) {
    functions.logger.error('PubSub message was not JSON', e);
  }

Pub/Sub 메시지에서 JSON이 아닌 기타 페이로드는 메시지 객체에 base64 인코딩 문자열로 포함됩니다. 다음과 같은 메시지를 읽으려면 아래와 같이 base64 인코딩 문자열을 디코딩해야 합니다.

gcloud pubsub topics publish topic-name --message 'MyMessage'

// Decode the PubSub Message body.
const messageBody = message.data ? Buffer.from(message.data, 'base64').toString() : null;

메시지 속성에 액세스{:#access-message}

Pub/Sub 메시지는 게시 명령어에 설정된 데이터 속성과 함께 전송될 수 있습니다. 예를 들어 name 속성과 함께 메시지를 게시할 수 있습니다.

gcloud pubsub topics publish topic-name --attribute name=Xenia

Message.attributes에서 이러한 속성을 읽을 수 있습니다.

// Get the `name` attribute of the message.
const name = message.attributes.name;

Message.attributes에 메시지 ID 또는 메시지 게시 시간과 같은 몇 가지 기본적인 데이터가 없을 수 있습니다. 이 문제를 해결하려면 트리거 이벤트의 EventContext에서 세부정보에 액세스하면 됩니다. 예를 들면 다음과 같습니다.

exports.myFunction = functions.pubsub.topic('topic1').onPublish((message, context) => {
    console.log('The function was triggered at ', context.timestamp);
    console.log('The unique ID for the event is', context.eventId);
});