Pub/Sub 트리거


Google CloudPub/Sub는 필요에 따라 자동으로 확장되는 글로벌 분산형 메시지 버스입니다. 새 Pub/Sub 메시지가 특정 주제로 전송될 때마다 함수를 트리거할 수 있습니다.

필수 모듈 가져오기

시작하려면 Pub/Sub 이벤트 처리에 필요한 모듈을 가져옵니다.

Node.jsPython
const {onMessagePublished} = require("firebase-functions/v2/pubsub");
const logger = require("firebase-functions/logger");
from firebase_functions import pubsub_fn

함수 트리거

함수를 트리거할 Pub/Sub 주제 이름을 지정하고 이벤트 핸들러 내에서 이벤트를 설정해야 합니다.

Node.jsPython
exports.hellopubsub = onMessagePublished("topic-name", (event) => {
@pubsub_fn.on_message_published(topic="topic-name")
def hellopubsub(event: pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData]) -> None:
    """Log a message using data published to a Pub/Sub topic."""

Pub/Sub 메시지 페이로드에 액세스

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

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

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

Node.jsPython
  // Get the `name` attribute of the PubSub message JSON body.
  let name = null;
  try {
    name = event.data.message.json.name;
  } catch (e) {
    logger.error("PubSub message was not JSON", e);
  }
# Get the `name` attribute of the PubSub message JSON body.
try:
    data = event.data.message.json
except ValueError:
    print("PubSub message was not JSON")
    return
if data is None:
    return
if "name" not in data:
    print("No 'name' key")
    return
name = data["name"]

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

gcloud pubsub topics publish topic-name --message 'MyMessage'
Node.jsPython
// Decode the PubSub Message body.
const message = event.data.message;
const messageBody = message.data ?
      Buffer.from(message.data, "base64").toString() :
      null;
# Decode the PubSub message body.
message_body = base64.b64decode(event.data.message.data)

메시지 속성에 액세스

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

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

메시지 객체의 해당 속성에서 이러한 속성을 읽을 수 있습니다.

Node.jsPython
// Get the `name` attribute of the message.
const name = event.data.message.attributes.name;
# Get the `name` attribute of the message.
if "name" not in event.data.message.attributes:
    print("No 'name' attribute")
    return
name = event.data.message.attributes["name"]