分离订阅

创建订阅时,您将订阅附加到主题,然后订阅者可以接收来自订阅的消息。要停止订阅 则您可以将订阅与主题分离。

在分离订阅之前,您需要对该主题的 pubsub.topics.detachSubscription 权限。您可以在没有订阅权限的情况下分离订阅,这有助于管理与订阅处于不同项目中的主题。如需了解详情,请参阅 Pub/Sub 访问权限控制

准备工作

所需的角色和权限

如需获得解除订阅和管理订阅所需的权限,请让您的管理员为您授予主题或项目的 Pub/Sub Editor (roles/pubsub.editor) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

此预定义角色包含 分离和管理订阅所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

如需解除订阅和管理订阅,您需要具备以下权限:

  • 从订阅中拉取: pubsub.subscriptions.consume
  • 创建订阅: pubsub.subscriptions.create
  • 删除订阅: pubsub.subscriptions.delete
  • 获取订阅: pubsub.subscriptions.get
  • 列出订阅: pubsub.subscriptions.list
  • 更新订阅: pubsub.subscriptions.update
  • 将订阅附加到主题: pubsub.topics.attachSubscription
  • 获取订阅的 IAM 政策: pubsub.subscriptions.getIamPolicy
  • 为订阅配置 IAM 政策 pubsub.subscriptions.setIamPolicy

您也可以使用自定义角色或其他预定义角色来获取这些权限。

您可以在项目级别和各个资源级别配置访问权限控制。您可以在一个项目中创建订阅,并将其附加到位于其他项目中的主题。确保您拥有 资源。

将订阅与主题分离

您可以使用 Google Cloud 控制台、 Google Cloud CLI、客户端库或 Pub/Sub API。

控制台

要分离订阅,请按以下步骤操作:

  1. 在 Google Cloud 控制台中,前往主题页面。

    转到“主题”

  2. 选择要从中分离订阅的主题。

  3. 订阅标签页中,选择要分离的订阅。

  4. 订阅详情页面中,点击分离

  5. 在显示的对话框中,再次点击分离

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 topics detach-subscription 命令:

    gcloud pubsub topics detach-subscription SUBSCRIPTION_ID

    如果请求成功,命令行会显示一条确认消息:

    Detached subscription [SUBSCRIPTION_ID].

REST

如需分离订阅,请使用 projects.subscriptions.detach 方法。

请求:

必须使用 Authorization 标头中的访问令牌对请求进行身份验证。如需获取当前应用默认凭据的访问令牌,请使用 gcloud auth application-default print-access-token 命令。

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

其中:

  • PROJECT_ID 是项目 ID。
  • SUBSCRIPTION_ID 是您的订阅 ID。
  • 回答:

    如果请求成功,响应将为空的 JSON 对象。

    C++

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C++ 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C++ API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    namespace pubsub = ::google::cloud::pubsub;
    namespace pubsub_admin = ::google::cloud::pubsub_admin;
    [](pubsub_admin::TopicAdminClient client, std::string const& project_id,
       std::string const& subscription_id) {
      google::pubsub::v1::DetachSubscriptionRequest request;
      request.set_subscription(
          pubsub::Subscription(project_id, subscription_id).FullName());
      auto response = client.DetachSubscription(request);
      if (!response.ok()) throw std::move(response).status();
    
      std::cout << "The subscription was successfully detached: "
                << response->DebugString() << "\n";
    }

    C#

    在尝试此示例之前,请按照C# Pub/Sub 快速入门: 客户端库。 有关详情,请参阅 Pub/Sub C# API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    
    using Google.Cloud.PubSub.V1;
    using System;
    
    public class DetachSubscriptionSample
    {
        public void DetachSubscription(string projectId, string subscriptionId)
        {
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
    
            DetachSubscriptionRequest detachSubscriptionRequest = new DetachSubscriptionRequest
            {
                SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
            };
    
            publisher.DetachSubscription(detachSubscriptionRequest);
    
            Console.WriteLine($"Subscription {subscriptionId} is detached.");
        }
    }

    Go

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/pubsub"
    )
    
    func detachSubscription(w io.Writer, projectID, subName string) error {
    	// projectID is the project which contains the topic you manage.
    	// This might differ from the project which contains the subscription
    	// you wish to detach, which can exist in any GCP project.
    	// projectID := "my-project-id"
    	// subName := "projects/some-project/subscriptions/my-sub"
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	// Call DetachSubscription, which detaches a subscription from
    	// a topic. This can only be done if you have the
    	// `pubsub.topics.detachSubscription` role on the topic.
    	_, err = client.DetachSubscription(ctx, subName)
    	if err != nil {
    		return fmt.Errorf("detach subscription failed: %w", err)
    	}
    
    	fmt.Fprintf(w, "Detached subscription %s", subName)
    	return nil
    }
    

    Java

    在尝试此示例之前,请按照Java Pub/Sub 快速入门: 客户端库。 如需了解详情,请参阅 Pub/Sub Java API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
    import com.google.cloud.pubsub.v1.TopicAdminClient;
    import com.google.pubsub.v1.DetachSubscriptionRequest;
    import com.google.pubsub.v1.Subscription;
    import com.google.pubsub.v1.SubscriptionName;
    import java.io.IOException;
    
    public class DetachSubscriptionExample {
      public static void main(String... args) throws Exception {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        // Choose an existing subscription.
        String subscriptionId = "your-subscription-id";
    
        detachSubscriptionExample(projectId, subscriptionId);
      }
    
      public static void detachSubscriptionExample(String projectId, String subscriptionId)
          throws IOException {
        SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
    
        try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
          topicAdminClient.detachSubscription(
              DetachSubscriptionRequest.newBuilder()
                  .setSubscription(subscriptionName.toString())
                  .build());
        }
    
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
          Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
          if (subscription.getDetached()) {
            System.out.println("Subscription is detached.");
          } else {
            System.out.println("Subscription is NOT detached.");
          }
        }
      }
    }

    Node.js

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const subscriptionNameOrId = 'YOUR_EXISTING_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 detachSubscription(subscriptionNameOrId) {
      // Gets the status of the existing subscription
      const sub = pubSubClient.subscription(subscriptionNameOrId);
      const [detached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`
      );
    
      await pubSubClient.detachSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);
    
      const [updatedDetached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`
      );
    }

    Node.js

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const subscriptionNameOrId = 'YOUR_EXISTING_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 detachSubscription(subscriptionNameOrId: string) {
      // Gets the status of the existing subscription
      const sub = pubSubClient.subscription(subscriptionNameOrId);
      const [detached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`
      );
    
      await pubSubClient.detachSubscription(subscriptionNameOrId);
      console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);
    
      const [updatedDetached] = await sub.detached();
      console.log(
        `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`
      );
    }

    PHP

    在尝试此示例之前,请按照PHP Pub/Sub 快速入门: 客户端库。 如需了解详情,请参阅 Pub/Sub PHP API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

    Python

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。 有关详情,请参阅 Pub/Sub Python API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    from google.api_core.exceptions import GoogleAPICallError, RetryError
    from google.cloud import pubsub_v1
    
    # TODO(developer): Choose an existing subscription.
    # project_id = "your-project-id"
    # subscription_id = "your-subscription-id"
    
    publisher_client = pubsub_v1.PublisherClient()
    subscriber_client = pubsub_v1.SubscriberClient()
    subscription_path = subscriber_client.subscription_path(project_id, subscription_id)
    
    try:
        publisher_client.detach_subscription(
            request={"subscription": subscription_path}
        )
    except (GoogleAPICallError, RetryError, ValueError, Exception) as err:
        print(err)
    
    subscription = subscriber_client.get_subscription(
        request={"subscription": subscription_path}
    )
    if subscription.detached:
        print(f"{subscription_path} is detached.")
    else:
        print(f"{subscription_path} is NOT detached.")

    Ruby

    在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档

    如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

    # subscription_id = "your-subscription-id"
    
    pubsub = Google::Cloud::Pubsub.new
    
    subscription = pubsub.subscription subscription_id
    subscription.detach
    
    sleep 120
    subscription.reload!
    if subscription.detached?
      puts "Subscription is detached."
    else
      puts "Subscription is NOT detached."
    end

    Pub/Sub 服务可能需要几分钟才能完成对主题的订阅分离。

    Pub/Sub 服务将订阅与主题分离后,Pub/Sub 服务会删除它为订阅保留的所有消息。您不能从订阅中检索这些消息,也无法将订阅重新附加到主题。如需释放 Google Cloud 项目配额,请删除订阅

    如果订阅和主题位于不同的 Google Cloud 项目中, Pub/Sub 服务会在两个项目的审核日志中添加一个条目。

    后续步骤