解除包裝 Pub/Sub 推送訂閱項目的酬載

建構 Pub/Sub 系統時,您可以透過酬載解除包裝,連線至不遵循標準 Pub/Sub 推送端點實作項目的所有系統。

以下是一些可能的酬載解封用途:

  • 您不想為 HTTP 推送端點編寫 Pub/Sub 專屬的訊息剖析程式碼。
  • 您希望以 HTTP 標頭的形式接收 Pub/Sub 訊息中繼資料,而不是在 HTTP POST 主體中接收中繼資料。
  • 您想傳送 Pub/Sub 訊息,並排除 Pub/Sub 中繼資料,例如傳送資料至第三方 API 時。

酬載解除包裝的運作方式

酬載解除包裝功能會移除 Pub/Sub 訊息中的所有訊息中繼資料 (除了訊息資料)。透過傳送原始訊息資料,訂閱者就能處理訊息,而無須遵守 Pub/Sub 的任何系統規定。

  • 透過酬載展開,訊息資料會直接以 HTTP 內文的形式傳送。
  • 如果未解除酬載包裝,Pub/Sub 會傳送 JSON 物件,其中包含多個訊息中繼資料欄位和訊息資料欄位。在這種情況下,您必須剖析 JSON 才能擷取訊息資料,然後再進行 base64 解碼。

寫入中繼資料

啟用酬載解除包裝後,您可以使用「寫入中繼資料」選項,將先前移除的訊息中繼資料新增至要求標頭

  • 已啟用寫入中繼資料功能。將訊息中繼資料重新加入要求標頭。也傳送已解碼的原始訊息資料。
  • 寫入中繼資料功能已停用。只傳送已解碼的原始訊息資料。

寫入中繼資料會透過 Pub/Sub、Google Cloud CLI 引數 --push-no-wrapper-write-metadata 和 API 屬性 NoWrapper 公開。根據預設,這個值為 null。

事前準備

已包裝和未包裝訊息的範例

以下範例說明傳送已包裝和未包裝 HTTP 訊息的差異。在這些範例中,訊息資料包含字串 {"status": "Hello there"}

在這個範例中,我們會建立訂閱項目,並啟用酬載解封功能,然後將訊息發布至 mytopic。它使用排序鍵,其值為 some-key,且媒體類型已宣告為 application/json

gcloud pubsub topics publish mytopic
   --message='{"status": "Hello there"}'
   --ordering-key="some-key"
   --attribute "Content-Type=application/json"

以下各節說明包裝和未包裝訊息的差異。

已換行的訊息

以下範例顯示標準的 Pub/Sub 包裝訊息。在這種情況下,系統不會啟用酬載解除包裝功能。

發布 推送端點接收
data="{"status": "Hello there"}"
ordering_key="some-key"
attributes=
  {
     {"Content-Type", "application/json"}
  }
Content-Length: 361
Content-Type: application/json
User-Agent: CloudPubSub-Google
Host: subscription-project.uc.r.appspot.com

{
  "message": {
      "attributes": {
          "Content-Type": "application/json"
      },
      "data": "eyJzdGF0dXMiOiAiSGVsbG8gdGhlcmUifQ==", //  Base64 - {"status": "Hello there"}
      "messageId": "2070443601311540",
      "message_id": "2070443601311540",
      "publishTime": "2021-02-26T19:13:55.749Z",
      "publish_time": "2021-02-26T19:13:55.749Z"
  },
  "subscription": "projects/myproject/..."
}

已解除包裝的訊息,且已停用寫入中繼資料

以下範例顯示已停用的寫入中繼資料選項的展開訊息。在這種情況下,系統不會加入 x-goog-pubsub-* 標頭和訊息屬性

發布 推送端點接收
data="{"status": "Hello there"}"
ordering_key="some-key"
attributes=
  {
     {"Content-Type", "application/json"}
  }
Content-Length: 25
User-Agent: CloudPubSub-Google
Host: subscription-project.uc.r.appspot.com

{"status": "Hello there"}

已啟用寫入中繼資料的解除包裝訊息

以下範例顯示已啟用寫入中繼資料選項的展開訊息。在本例中,系統會納入 x-goog-pubsub-* 標頭和訊息屬性

發布 推送端點接收
data="{"status": "Hello there"}"
ordering_key="some-key"
attributes=
  {
     {"Content-Type", "application/json"}
  }
x-goog-pubsub-subscription-name: "projects/myproject/..."
x-goog-pubsub-message-id: "2070443601311540"
x-goog-pubsub-publish-time: "2021-02-26T19:13:55.749Z"
x-goog-pubsub-ordering-key: "some-key"
Content-Type: application/json
Content-Length: 12
User-Agent: CloudPubSub-Google
Host: subscription-project.uc.r.appspot.com

{"status": "Hello there"}

設定酬載解除包裝

您可以使用 Google Cloud 控制台「訂閱詳細資料」頁面、Google Cloud CLI 或用戶端程式庫,為訂閱啟用酬載展開推送傳送功能。

控制台

  1. 在 Google Cloud 控制台中,前往「訂閱項目」頁面。

    開啟 Pub/Sub 訂閱項目

  2. 按一下「Create Subscription」 (建立訂閱項目)

  3. 在「Subscription ID」(訂閱項目 ID) 欄位中輸入名稱。

    如要瞭解如何命名訂閱項目,請參閱「命名主題或訂閱項目的規範」。

  4. 從下拉式選單中選取主題。訂閱項目會接收主題的訊息。

  5. 在「Delivery type」(傳送類型) 中,選取「Push」(推送)

  6. 如要啟用酬載解除包裝功能,請選取「啟用酬載解除包裝功能」

  7. (選用) 如要保留要求標頭中的訊息中繼資料,請選取「Write metadata」。您必須啟用這個選項,才能為郵件設定 Content-Type 標頭

  8. 指定端點網址。

  9. 保留所有其他預設值。

  10. 按一下 [建立]。

gcloud

如要設定訂閱項目,並包含標準 HTTP 標頭的酬載解封裝,請執行下列 gcloud pubsub subscriptions create 指令:

gcloud pubsub subscriptions create SUBSCRIPTION \
  --topic TOPIC \
  --push-endpoint=PUSH_ENDPOINT \
  --push-no-wrapper

更改下列內容:

  • SUBSCRIPTION:拉取訂閱項目的名稱或 ID。
  • TOPIC:主題的 ID。
  • PUSH_ENDPOINT:要用來做為此訂閱項目端點的網址。例如:https://myproject.appspot.com/myhandler
  • --push-no-wrapper:直接以 HTTP 主體的形式傳送訊息資料。

如要設定訂閱項目,並透過酬載解開並控制 x-goog-pubsub-* 標頭的使用情形,請執行下列指令:

gcloud pubsub subscriptions create SUBSCRIPTION \
  --topic TOPIC \
  --push-endpoint=PUSH_ENDPOINT \
  --push-no-wrapper \
  --push-no-wrapper-write-metadata
  • --push-no-wrapper-write-metadata:如果為 true,系統會將 Pub/Sub 訊息中繼資料寫入 HTTP 要求的 x-goog-pubsub-<KEY>:<VAL> 標頭。將 Pub/Sub 訊息屬性寫入 HTTP 要求的 <KEY>:<VAL> 標頭。

Python

在嘗試這個範例之前,請先按照 快速入門:使用用戶端程式庫中的操作說明設定 Python 環境。詳情請參閱 Pub/Sub Python API 參考說明文件

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# endpoint = "https://my-test-project.appspot.com/push"

publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic_path = publisher.topic_path(project_id, topic_id)
subscription_path = subscriber.subscription_path(project_id, subscription_id)

no_wrapper = pubsub_v1.types.PushConfig.NoWrapper(write_metadata=True)
push_config = pubsub_v1.types.PushConfig(
    push_endpoint=endpoint, no_wrapper=no_wrapper
)

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    subscription = subscriber.create_subscription(
        request={
            "name": subscription_path,
            "topic": topic_path,
            "push_config": push_config,
        }
    )

print(f"Push no wrapper subscription created: {subscription}.")
print(f"Endpoint for subscription is: {endpoint}")
print(f"No wrapper configuration for subscription is: {no_wrapper}")

Java

在嘗試這個範例之前,請先按照 快速入門:使用用戶端程式庫中的操作說明設定 Java 環境。詳情請參閱 Pub/Sub Java API 參考說明文件

/*
 * Copyright 2016 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pubsub;


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.PushConfig.NoWrapper;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.SubscriptionName;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class CreateUnwrappedPushSubscriptionExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";
    String topicId = "your-topic-id";
    String pushEndpoint = "https://my-test-project.appspot.com/push";

    createPushSubscriptionExample(projectId, subscriptionId, topicId, pushEndpoint);
  }

  public static void createPushSubscriptionExample(
      String projectId, String subscriptionId, String topicId, String pushEndpoint)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
      NoWrapper noWrapper =
          NoWrapper.newBuilder()
              // Determines if message metadata is added to the HTTP headers of
              // the delivered message.
              .setWriteMetadata(true)
              .build();
      PushConfig pushConfig =
          PushConfig.newBuilder().setPushEndpoint(pushEndpoint).setNoWrapper(noWrapper).build();

      // Create a push subscription with default acknowledgement deadline of 10 seconds.
      // Messages not successfully acknowledged within 10 seconds will get resent by the server.
      Subscription subscription =
          subscriptionAdminClient.createSubscription(subscriptionName, topicName, pushConfig, 10);
      System.out.println("Created push subscription: " + subscription.getName());
    }
  }
}

C++

在嘗試這個範例之前,請先按照 快速入門:使用用戶端程式庫中的操作說明設定 C++ 環境。詳情請參閱 Pub/Sub C++ API 參考說明文件

namespace pubsub = ::google::cloud::pubsub;
namespace pubsub_admin = ::google::cloud::pubsub_admin;
[](pubsub_admin::SubscriptionAdminClient client,
   std::string const& project_id, std::string const& topic_id,
   std::string const& subscription_id, std::string const& endpoint) {
  google::pubsub::v1::Subscription request;
  request.set_name(
      pubsub::Subscription(project_id, subscription_id).FullName());
  request.set_topic(pubsub::Topic(project_id, topic_id).FullName());
  request.mutable_push_config()->set_push_endpoint(endpoint);
  request.mutable_push_config()->mutable_no_wrapper()->set_write_metadata(
      true);
  auto sub = client.CreateSubscription(request);
  if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The subscription already exists\n";
    return;
  }
  if (!sub) throw std::move(sub).status();

  std::cout << "The subscription was successfully created: "
            << sub->DebugString() << "\n";
}

Go

在試用這個範例之前,請先按照 快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 Pub/Sub Go API 參考說明文件

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/pubsub"
)

// createPushNoWrapperSubscription creates a push subscription where messages are delivered in the HTTP body.
func createPushNoWrapperSubscription(w io.Writer, projectID, subID string, topic *pubsub.Topic, endpoint string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	// topic of type https://godoc.org/cloud.google.com/go/pubsub#Topic
	// endpoint := "https://my-test-project.appspot.com/push"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	sub, err := client.CreateSubscription(ctx, subID, pubsub.SubscriptionConfig{
		Topic:       topic,
		AckDeadline: 10 * time.Second,
		PushConfig: pubsub.PushConfig{
			Endpoint: endpoint,
			Wrapper: &pubsub.NoWrapper{
				// Determines if message metadata is added to the HTTP headers of
				// the delivered message.
				WriteMetadata: true,
			},
		},
	})
	if err != nil {
		return fmt.Errorf("CreateSubscription: %w", err)
	}
	fmt.Fprintf(w, "Created push no wrapper subscription: %v\n", sub)
	return nil
}

Node.js

在嘗試這個範例之前,請先按照 快速入門:使用用戶端程式庫中的操作說明設定 Node.js 環境。詳情請參閱 Pub/Sub Node.js API 參考說明文件

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const pushEndpoint = 'YOUR_ENDPOINT_URL';
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createPushSubscriptionNoWrapper(
  pushEndpoint,
  topicNameOrId,
  subscriptionNameOrId,
) {
  const options = {
    pushConfig: {
      // Set to an HTTPS endpoint of your choice. If necessary, register
      // (authorize) the domain on which the server is hosted.
      pushEndpoint,
      // When true, writes the Pub/Sub message metadata to
      // `x-goog-pubsub-<KEY>:<VAL>` headers of the HTTP request. Writes the
      // Pub/Sub message attributes to `<KEY>:<VAL>` headers of the HTTP request.
      noWrapper: {
        writeMetadata: true,
      },
    },
  };

  await pubSubClient
    .topic(topicNameOrId)
    .createSubscription(subscriptionNameOrId, options);
  console.log(`Subscription ${subscriptionNameOrId} created.`);
}

Node.js

在嘗試這個範例之前,請先按照 快速入門:使用用戶端程式庫中的操作說明設定 Node.js 環境。詳情請參閱 Pub/Sub Node.js API 參考說明文件

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const pushEndpoint = 'YOUR_ENDPOINT_URL';
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// Imports the Google Cloud client library
import {PubSub, CreateSubscriptionOptions} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createPushSubscriptionNoWrapper(
  pushEndpoint: string,
  topicNameOrId: string,
  subscriptionNameOrId: string,
) {
  const options: CreateSubscriptionOptions = {
    pushConfig: {
      // Set to an HTTPS endpoint of your choice. If necessary, register
      // (authorize) the domain on which the server is hosted.
      pushEndpoint,
      // When true, writes the Pub/Sub message metadata to
      // `x-goog-pubsub-<KEY>:<VAL>` headers of the HTTP request. Writes the
      // Pub/Sub message attributes to `<KEY>:<VAL>` headers of the HTTP request.
      noWrapper: {
        writeMetadata: true,
      },
    },
  };

  await pubSubClient
    .topic(topicNameOrId)
    .createSubscription(subscriptionNameOrId, options);
  console.log(`Subscription ${subscriptionNameOrId} created.`);
}

在郵件中設定內容類型標頭

啟用酬載展開功能後,Pub/Sub 不會在要求中自動設定媒體類型標頭欄位。如果您未明確設定 Content-Type 標頭欄位,處理您要求的網頁伺服器可能會設定 application/octet-stream 的預設值,或以意料之外的方式解讀要求。

如果您需要 Content-Type 標頭,請務必在發布時明確宣告每個已發布訊息。為此,您必須先啟用「Write metadata」提供的範例顯示啟用「Write metadata」的結果。

後續步驟