将订阅与主题分离

当主题管理员客户端分离订阅时,订阅不再允许读取该主题中的任何数据,且舍弃此订阅上存储的消息(未确认和确认)。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

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#

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C# 设置说明进行操作。 如需了解详情,请参阅 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

在尝试此示例之前,请按照Go Pub/Sub 快速入门: 客户端库。 有关详情,请参阅 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

在尝试此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器