建立提取訂閱項目

本文件說明如何建立提取訂閱。您可以使用 Google Cloud 控制台、Google Cloud CLI、用戶端程式庫或 Pub/Sub API 建立提取訂閱。

事前準備

必要角色和權限

如要建立訂閱項目,您必須在專案層級設定存取權控管。如果訂閱項目和主題位於不同專案中,您也需要資源層級權限,請參閱本節後續的說明。

如要取得建立拉取訂閱所需的權限,請要求管理員為您授予專案的 Pub/Sub 編輯者 (roles/pubsub.editor) 身分與存取權管理角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色包含建立拉取訂閱所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要建立提取訂閱項目,您必須具備下列權限:

  • 從訂閱項目提取: pubsub.subscriptions.consume
  • 建立訂閱項目: pubsub.subscriptions.create
  • 刪除訂閱項目: pubsub.subscriptions.delete
  • 取得訂閱項目: pubsub.subscriptions.get
  • 列出訂閱項目: pubsub.subscriptions.list
  • 更新訂閱: pubsub.subscriptions.update
  • 將訂閱項目附加至主題: pubsub.topics.attachSubscription
  • 取得訂閱項目的身分與存取權管理政策: pubsub.subscriptions.getIamPolicy
  • 設定訂閱項目的 IAM 政策 pubsub.subscriptions.setIamPolicy

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

如果您需要在一個專案中建立與另一個專案主題相關的拉取訂閱項目,請要求主題管理員也將 Pub/Sub 編輯者 (roles/pubsub.editor) IAM 角色授予您。

提取訂閱項目屬性

設定拉取訂閱時,您可以指定下列屬性。

常見屬性

瞭解您可以在所有訂閱項目中設定的常見訂閱屬性

僅傳送一次

僅傳送一次:如果已設定,Pub/Sub 就會履行「僅傳送一次」傳送保證。如果未指定,訂閱項目會支援每則訊息的至少一次傳送。

建立提取訂閱項目

以下範例示範如何使用提供的預設設定,建立使用提取提交的訂閱項目。

控制台

如要建立提取訂閱,請完成下列步驟。

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

    前往「訂閱項目」頁面

  2. 按一下「Create Subscription」 (建立訂閱項目)
  3. 在「Subscription ID」欄位中輸入名稱。

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

  4. 從下拉式選單中選擇或建立主題。訂閱項目會接收主題的訊息。
  5. 將「Delivery type」保留為「提取」
  6. 保留所有其他預設值。
  7. 按一下 [建立]。

您也可以在「主題」部分建立訂閱項目。 這個快捷動作可用於將主題與訂閱項目建立關聯。

  1. 前往 Google Cloud 控制台的「Topics」頁面。

    前往「主題」

  2. 按一下要建立訂閱的主題旁邊的
  3. 在內容選單中,選取「建立訂閱」
  4. 輸入「Subscription ID」(訂閱 ID)

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

  5. 將「Delivery type」保留為「提取」
  6. 保留所有其他預設值。
  7. 按一下 [建立]。

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 如要建立提取訂閱,請執行 gcloud pubsub subscriptions create 指令
    gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic=TOPIC_ID

    更改下列內容:

    • SUBSCRIPTION_ID:新拉取訂閱項目的名稱或 ID。
    • TOPIC_ID:主題的名稱或 ID。

REST

如要建立提取訂閱,請使用 projects.subscriptions.create 方法:

要求:

要求必須透過 Authorization 標頭中的存取權權杖進行驗證。如要取得目前應用程式預設憑證的存取權杖,請執行以下操作: gcloud auth application-default print-access-token

PUT https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer ACCESS_TOKEN

要求主體:

{
  "topic": "projects/PROJECT_ID/topics/TOPIC_ID"
}

其中:

  • PROJECT_ID 是您的專案 ID。
  • SUBSCRIPTION_ID 是訂閱項目 ID。
  • TOPIC_ID 是主題 ID。
  • 回應:

    {
      "name": "projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID",
      "topic": "projects/PROJECT_ID/topics/TOPIC_ID",
      "pushConfig": {},
      "ackDeadlineSeconds": 10,
      "messageRetentionDuration": "604800s",
      "expirationPolicy": {
        "ttl": "2678400s"
      }
    }

    C++

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

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

    namespace pubsub_admin = ::google::cloud::pubsub_admin;
    namespace pubsub = ::google::cloud::pubsub;
    [](pubsub_admin::SubscriptionAdminClient client,
       std::string const& project_id, std::string const& topic_id,
       std::string const& subscription_id) {
      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());
      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";
    }

    C#

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

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

    
    using Google.Cloud.PubSub.V1;
    using Grpc.Core;
    
    public class CreateSubscriptionSample
    {
        public Subscription CreateSubscription(string projectId, string topicId, string subscriptionId)
        {
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
            TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
    
            SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
            Subscription subscription = null;
    
            try
            {
                subscription = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
            }
            catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
            {
                // Already exists.  That's fine.
            }
            return subscription;
        }
    }

    Go

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

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	"cloud.google.com/go/pubsub"
    )
    
    func create(w io.Writer, projectID, subID string, topic *pubsub.Topic) error {
    	// projectID := "my-project-id"
    	// subID := "my-sub"
    	// topic of type https://godoc.org/cloud.google.com/go/pubsub#Topic
    	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: 20 * time.Second,
    	})
    	if err != nil {
    		return fmt.Errorf("CreateSubscription: %w", err)
    	}
    	fmt.Fprintf(w, "Created subscription: %v\n", sub)
    	return nil
    }
    

    Java

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

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

    
    import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
    import com.google.pubsub.v1.PushConfig;
    import com.google.pubsub.v1.Subscription;
    import com.google.pubsub.v1.SubscriptionName;
    import com.google.pubsub.v1.TopicName;
    import java.io.IOException;
    
    public class CreatePullSubscriptionExample {
      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";
    
        createPullSubscriptionExample(projectId, subscriptionId, topicId);
      }
    
      public static void createPullSubscriptionExample(
          String projectId, String subscriptionId, String topicId) throws IOException {
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
          TopicName topicName = TopicName.of(projectId, topicId);
          SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
          // Create a pull 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.getDefaultInstance(), 10);
          System.out.println("Created pull subscription: " + subscription.getName());
        }
      }
    }

    Node.js

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // 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 createSubscription(topicNameOrId, subscriptionNameOrId) {
      // Creates a new subscription
      await pubSubClient
        .topic(topicNameOrId)
        .createSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} created.`);
    }

    Node.js

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
    // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';
    
    // Imports the Google Cloud client library
    import {PubSub} from '@google-cloud/pubsub';
    
    // Creates a client; cache this for further use
    const pubSubClient = new PubSub();
    
    async function createSubscription(
      topicNameOrId: string,
      subscriptionNameOrId: string,
    ) {
      // Creates a new subscription
      await pubSubClient
        .topic(topicNameOrId)
        .createSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} created.`);
    }

    PHP

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

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

    use Google\Cloud\PubSub\PubSubClient;
    
    /**
     * Creates a Pub/Sub subscription.
     *
     * @param string $projectId  The Google project ID.
     * @param string $topicName  The Pub/Sub topic name.
     * @param string $subscriptionName  The Pub/Sub subscription name.
     */
    function create_subscription($projectId, $topicName, $subscriptionName)
    {
        $pubsub = new PubSubClient([
            'projectId' => $projectId,
        ]);
        $topic = $pubsub->topic($topicName);
        $subscription = $topic->subscription($subscriptionName);
        $subscription->create();
    
        printf('Subscription created: %s' . PHP_EOL, $subscription->name());
    }

    Python

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

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

    from google.cloud import pubsub_v1
    
    # TODO(developer)
    # project_id = "your-project-id"
    # topic_id = "your-topic-id"
    # subscription_id = "your-subscription-id"
    
    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)
    
    # 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}
        )
    
    print(f"Subscription created: {subscription}")

    Ruby

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

    如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

    # topic_id        = "your-topic-id"
    # subscription_id = "your-subscription-id"
    
    pubsub = Google::Cloud::Pubsub.new
    
    topic        = pubsub.topic topic_id
    subscription = topic.subscribe subscription_id
    
    puts "Pull subscription #{subscription_id} created."

    監控提取訂閱項目

    Cloud Monitoring 提供多項指標,可用於監控訂閱項目

    如需 Pub/Sub 相關指標的完整清單和說明,請參閱 Pub/Sub 監控說明文件

    您也可以在 Pub/Sub 中監控訂閱項目。

    後續步驟