Pub/Sub 트리거


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

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 FunctionsFirebase 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);
  }

JSON이 아닌 기타 페이로드는 Pub/Sub 메시지에 다음과 같이 포함됩니다. 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 메시지는 publish 명령어를 사용하여 예를 들어 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);
});