管理主题和订阅

本文档介绍如何创建、删除和管理 Pub/Sub 主题和订阅。如需详细了解如何发布和访问消息数据,请参阅发布者指南订阅者概览

管理主题

您可以使用 API、Google Cloud Console 或 gcloud 命令行工具来创建、删除和查看主题。如需查看 Pub/Sub API gcloud 命令的完整列表,请参阅 gcloud pubsub 参考文档

创建主题

您必须先创建一个主题,然后才能向其发布消息或订阅该主题。 以下示例说明了如何创建主题:

gcloud

gcloud pubsub topics create TOPIC_ID

REST

请求:

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

PUT https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic
Authorization: Bearer ACCESS_TOKEN
    

响应:

200 OK
{
 "name": "projects/myproject/topics/mytopic"
}

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string project_id,
   std::string topic_id) {
  auto topic = client.CreateTopic(pubsub::TopicBuilder(
      pubsub::Topic(std::move(project_id), std::move(topic_id))));
  // Note that kAlreadyExists is a possible error when the library retries.
  if (topic.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The topic already exists\n";
    return;
  }
  if (!topic) throw std::runtime_error(topic.status().message());

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

C#

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


using Google.Cloud.PubSub.V1;
using Grpc.Core;
using System;

public class CreateTopicSample
{
    public Topic CreateTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        var topicName = TopicName.FromProjectTopic(projectId, topicId);
        Topic topic = null;

        try
        {
            topic = publisher.CreateTopic(topicName);
            Console.WriteLine($"Topic {topic.Name} created.");
        }
        catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            Console.WriteLine($"Topic {topicName} already exists.");
        }
        return topic;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

func create(w io.Writer, projectID, topicID string) error {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	t, err := client.CreateTopic(ctx, topicID)
	if err != nil {
		return fmt.Errorf("CreateTopic: %v", err)
	}
	fmt.Fprintf(w, "Topic created: %v\n", t)
	return nil
}

Java

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


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class CreateTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    createTopicExample(projectId, topicId);
  }

  public static void createTopicExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      Topic topic = topicAdminClient.createTopic(topicName);
      System.out.println("Created topic: " + topic.getName());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

// 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 createTopic() {
  // Creates a new topic
  await pubSubClient.createTopic(topicName);
  console.log(`Topic ${topicName} created.`);
}

createTopic();

PHP

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

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function create_topic($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->createTopic($topicName);

    printf('Topic created: %s' . PHP_EOL, $topic->name());
}

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)

topic = publisher.create_topic(request={"name": topic_path})

print("Created topic: {}".format(topic.name))

Ruby

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

# topic_id = "your-topic-id"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topic = pubsub.create_topic topic_id

puts "Topic #{topic.name} created."

删除主题

以下示例说明了如何删除主题:

gcloud

gcloud pubsub topics delete TOPIC_ID

REST

请求:

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

DELETE https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic
Authorization: Bearer ACCESS_TOKEN
    

响应:

200 OK
{
 "name": "projects/myproject/topics/mytopic"
}

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string const& project_id,
   std::string const& topic_id) {
  auto status = client.DeleteTopic(
      pubsub::Topic(std::move(project_id), std::move(topic_id)));
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The topic was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The topic was successfully deleted\n";
}

C#

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


using Google.Cloud.PubSub.V1;

public class DeleteTopicSample
{
    public void DeleteTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        publisher.DeleteTopic(topicName);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

func delete(w io.Writer, projectID, topicID string) error {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	t := client.Topic(topicID)
	if err := t.Delete(ctx); err != nil {
		return fmt.Errorf("Delete: %v", err)
	}
	fmt.Fprintf(w, "Deleted topic: %v\n", t)
	return nil
}

Java

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


import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class DeleteTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    deleteTopicExample(projectId, topicId);
  }

  public static void deleteTopicExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      try {
        topicAdminClient.deleteTopic(topicName);
        System.out.println("Deleted topic.");
      } catch (NotFoundException e) {
        System.out.println(e.getMessage());
      }
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

// 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 deleteTopic() {
  /**
   * TODO(developer): Uncomment the following line to run the sample.
   */
  // const topicName = 'my-topic';

  // Deletes the topic
  await pubSubClient.topic(topicName).delete();
  console.log(`Topic ${topicName} deleted.`);
}

deleteTopic().catch(console.error);

PHP

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

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function delete_topic($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $topic->delete();

    printf('Topic deleted: %s' . PHP_EOL, $topic->name());
}

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)

publisher.delete_topic(request={"topic": topic_path})

print("Topic deleted: {}".format(topic_path))

Ruby

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

# topic_id = "your-topic-id"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topic = pubsub.topic topic_id
topic.delete

puts "Topic #{topic_id} deleted."

当您删除某主题时,其订阅不会被删除,订阅的积压消息仍可供订阅者使用。在主题被删除后,其订阅的主题名称为 _deleted-topic_。如果您尝试创建与刚删除的主题名称相同的主题,则在删除后的短时间内会出现错误。

列出主题

以下示例说明了如何获取主题列表:

gcloud

gcloud pubsub topics list

REST

请求:

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

GET https://pubsub.googleapis.com/v1/projects/myproject/topics
Authorization: Bearer ACCESS_TOKEN
    

响应:

200 OK
{
  "topics": [
    {
      "name": "projects/myproject/topics/mytopic1"
    },
    {
      "name": "projects/myproject/topics/mytopic2"
    }
  ]
}

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string const& project_id) {
  int count = 0;
  for (auto const& topic : client.ListTopics(project_id)) {
    if (!topic) throw std::runtime_error(topic.status().message());
    std::cout << "Topic Name: " << topic->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No topics found in project " << project_id << "\n";
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListProjectTopicsSample
{
    public IEnumerable<Topic> ListProjectTopics(string projectId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        ProjectName projectName = ProjectName.FromProject(projectId);
        IEnumerable<Topic> topics = publisher.ListTopics(projectName);
        return topics;
    }
}

Go

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
)

func list(projectID string) ([]*pubsub.Topic, error) {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	var topics []*pubsub.Topic

	it := client.Topics(ctx)
	for {
		topic, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("Next: %v", err)
		}
		topics = append(topics, topic)
	}

	return topics, nil
}

Java

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


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Topic;
import java.io.IOException;

public class ListTopicsExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";

    listTopicsExample(projectId);
  }

  public static void listTopicsExample(String projectId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      ProjectName projectName = ProjectName.of(projectId);
      for (Topic topic : topicAdminClient.listTopics(projectName).iterateAll()) {
        System.out.println(topic.getName());
      }
      System.out.println("Listed all topics.");
    }
  }
}

Node.js

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

// 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 listAllTopics() {
  // Lists all topics in the current project
  const [topics] = await pubSubClient.getTopics();
  console.log('Topics:');
  topics.forEach(topic => console.log(topic.name));
}

listAllTopics().catch(console.error);

PHP

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

use Google\Cloud\PubSub\PubSubClient;

/**
 * Lists all Pub/Sub topics.
 *
 * @param string $projectId  The Google project ID.
 */
function list_topics($projectId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    foreach ($pubsub->topics() as $topic) {
        printf('Topic: %s' . PHP_EOL, $topic->name());
    }
}

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"

publisher = pubsub_v1.PublisherClient()
project_path = f"projects/{project_id}"

for topic in publisher.list_topics(request={"project": project_path}):
    print(topic)

Ruby

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

require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topics = pubsub.topics

puts "Topics in project:"
topics.each do |topic|
  puts topic.name
end

默认情况下,每个查询最多返回 100 个结果。 您可以使用页面大小参数指定一个其他值(最高 1000)。

分离订阅

创建订阅时,您将订阅附加到主题,然后订阅者可以接收来自订阅的消息。如需阻止订阅者接收消息,您可以分离对主题的订阅。

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

您可以使用 Cloud Console、gcloud 命令行工具或 Pub/Sub API 分离对主题的订阅。

控制台

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

  1. 在 Cloud Console 中,转到主题页面。

    转到“主题”页面

  2. 点击主题 ID。
  3. 订阅标签页中,点击要分离的订阅的订阅 ID。
  4. 订阅详情页面中,点击分离
  5. 在显示的对话框中,再次点击分离

gcloud

如需分离订阅,请使用 gcloud pubsub topics detach-subscription 命令:

gcloud pubsub topics detach-subscription SUBSCRIPTION_ID

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

Detached subscription [SUBSCRIPTION_ID].

REST

如需分离订阅,请发送如下请求:

POST https://pubsub.googleapis.com/v1/subscriptions/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:detach
Authorization: Bearer $(gcloud auth application-default print-access-token)

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

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string project_id,
   std::string subscription_id) {
  auto response = client.DetachSubscription(pubsub::Subscription(
      std::move(project_id), std::move(subscription_id)));
  if (!response.ok()) return;  // TODO(#4792) - not implemented in emulator

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

C#

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


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 参考文档

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: %v", 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: %v", err)
	}

	fmt.Fprintf(w, "Detached subscription %s", subName)
	return nil
}

Java

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

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.ProjectSubscriptionName;
import com.google.pubsub.v1.Subscription;
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 {
    ProjectSubscriptionName subscriptionName =
        ProjectSubscriptionName.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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const subscriptionName = 'YOUR_EXISTING_SUBSCRIPTION_NAME';

// 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() {
  // Gets the status of the existing subscription
  const sub = pubSubClient.subscription(subscriptionName);
  const [detached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionName} 'before' detached status: ${detached}`
  );

  await pubSubClient.detachSubscription(subscriptionName);
  console.log(`Subscription ${subscriptionName} detach request was sent.`);

  const [updatedDetached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionName} 'after' detached status: ${updatedDetached}`
  );
}

detachSubscription();

PHP

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

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 参考文档

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 参考文档

# subscription_id = "your-subscription-id"
require "google/cloud/pubsub"

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 服务会删除它为订阅保留的所有消息。您不能从订阅中检索这些消息,也无法将订阅重新附加到主题。如需释放 Cloud 项目配额,请删除订阅

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

管理订阅

本节介绍如何管理推送订阅和拉取订阅。如需查看拉取订阅和推送订阅的概览和比较,请参阅订阅者概览

您必须先为主题创建一个订阅,订阅者才能接收发布到该订阅的消息。

创建订阅

创建订阅时,您需要将主题附加到订阅。订阅者会收到发布者向该主题发送的消息。

您可以使用 Cloud Console、gcloud 命令行工具或 Pub/Sub API 创建订阅。

控制台

要创建订阅,请完成以下步骤。

  1. 在 Cloud Console 中,转到订阅页面。

    转到“订阅”页面

  2. 点击创建订阅
  3. 输入订阅 ID
  4. 从下拉菜单中选择或创建一个主题。订阅将接收来自该主题的消息。
  5. 点击创建

您还可以通过主题部分创建订阅。此快捷方式可帮助您将主题与订阅关联。

  1. 在 Cloud Console 中,转到主题页面。

    转到“主题”页面

  2. 点击要创建订阅的主题旁边的
  3. 从上下文菜单中,选择创建订阅

    突出显示“创建订阅”选项的上下文菜单。

  4. 从下拉菜单中选择或创建一个主题。订阅将接收来自该主题的消息。
  5. 输入订阅 ID
  6. 点击创建

gcloud

要创建订阅,请运行 gcloud pubsub subscriptions create 命令。

gcloud pubsub subscriptions create SUBSCRIPTION_ID \
    --topic=TOPIC_ID \
    [--ack-deadline=ACK_DEADLINE] \
    [--dead-letter-topic=DEAD_LETTER_TOPIC_ID \
    --dead-letter-topic-project=DEAD_LETTER_TOPIC_PROJECT_ID \
    [--expiration-period=EXPIRATION_PERIOD] \
    --max-delivery-attempts=MAX_DELIVERY_ATTEMPTS] \
    [--message-filter=FILTER]
    [--message-retention-duration=MESSAGE_RETENTION_DURATION] \
    [--max-retry-delay=MAX_RETRY_DELAY] \
    [--min-retry-delay=MIN_RETRY_DELAY] \
    [--push-endpoint=PUSH_ENDPOINT]

REST

请求:

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

PUT https://pubsub.googleapis.com/v1/projects/myproject/subscriptions/mysubscription
Authorization: Bearer ACCESS_TOKEN

在请求正文中指定以下字段:

{
  "topic": "projects/someproject/topics/sometopic"
  // Only needed if you are using push delivery
  "pushConfig": {
    "pushEndpoint": "https://myproject.appspot.com/myhandler"
  }
}

响应:

200 OK
{
  "name": "projects/myproject/subscriptions/mysubscription",
  "topic": "projects/someproject/topics/sometopic",
  "pushConfig": {
    "pushEndpoint": "https://myproject.appspot.com/myhandler"
  },
  "ackDeadlineSeconds": 10
}

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& topic_id, std::string const& subscription_id) {
  auto sub = client.CreateSubscription(
      pubsub::Topic(project_id, std::move(topic_id)),
      pubsub::Subscription(project_id, std::move(subscription_id)));
  if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The subscription already exists\n";
    return;
  }
  if (!sub) throw std::runtime_error(sub.status().message());

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

C#

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


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 参考文档

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: %v", err)
	}

	sub, err := client.CreateSubscription(ctx, subID, pubsub.SubscriptionConfig{
		Topic:       topic,
		AckDeadline: 20 * time.Second,
	})
	if err != nil {
		return fmt.Errorf("CreateSubscription: %v", err)
	}
	fmt.Fprintf(w, "Created subscription: %v\n", sub)
	return nil
}

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.Subscription;
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);
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

// 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() {
  // Creates a new subscription
  await pubSubClient.topic(topicName).createSubscription(subscriptionName);
  console.log(`Subscription ${subscriptionName} created.`);
}

createSubscription().catch(console.error);

PHP

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

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 参考文档

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 参考文档

# topic_id        = "your-topic-id"
# subscription_id = "your-subscription-id"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topic        = pubsub.topic topic_id
subscription = topic.subscribe subscription_id

puts "Pull subscription #{subscription_id} created."

以下示例演示了创建使用推送传送的订阅。默认情况下,订阅使用拉取传送

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& topic_id, std::string const& subscription_id,
   std::string const& endpoint) {
  auto sub = client.CreateSubscription(
      pubsub::Topic(project_id, std::move(topic_id)),
      pubsub::Subscription(project_id, std::move(subscription_id)),
      pubsub::SubscriptionBuilder{}.set_push_config(
          pubsub::PushConfigBuilder{}.set_push_endpoint(endpoint)));
  if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The subscription already exists\n";
    return;
  }
  if (!sub) throw std::runtime_error(sub.status().message());

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

C#

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


using Google.Cloud.PubSub.V1;

public class CreatePushSubscriptionSample
{
    public Subscription CreatePushSubscription(string projectId, string topicId, string subscriptionId, string pushEndpoint)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        PushConfig pushConfig = new PushConfig { PushEndpoint = pushEndpoint };

        // The approximate amount of time in seconds (on a best-effort basis) Pub/Sub waits for the
        // subscriber to acknowledge receipt before resending the message.
        var ackDeadlineSeconds = 60;
        var subscription = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig, ackDeadlineSeconds);
        return subscription;
    }
}

Go

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

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

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

func createWithEndpoint(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: %v", err)
	}

	sub, err := client.CreateSubscription(ctx, subID, pubsub.SubscriptionConfig{
		Topic:       topic,
		AckDeadline: 10 * time.Second,
		PushConfig:  pubsub.PushConfig{Endpoint: endpoint},
	})
	if err != nil {
		return fmt.Errorf("CreateSubscription: %v", err)
	}
	fmt.Fprintf(w, "Created subscription: %v\n", sub)
	return nil
}

Java

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


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

public class CreatePushSubscriptionExample {
  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);
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).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());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

// 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 createPushSubscription() {
  const options = {
    pushConfig: {
      // Set to an HTTPS endpoint of your choice. If necessary, register
      // (authorize) the domain on which the server is hosted.
      pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`,
    },
  };

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

createPushSubscription().catch(console.error);

PHP

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

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub push subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 * @param string $endpoint  The endpoint for the push subscription.
 */
function create_push_subscription($projectId, $topicName, $subscriptionName, $endpoint)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $subscription = $topic->subscription($subscriptionName);
    $subscription->create([
        'pushConfig' => ['pushEndpoint' => $endpoint]
    ]);

    printf('Subscription created: %s' . PHP_EOL, $subscription->name());
}

Python

在尝试此示例之前,请按照《Pub/Sub 快速入门:使用客户端库》中的 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)

push_config = pubsub_v1.types.PushConfig(push_endpoint=endpoint)

# 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 subscription created: {subscription}.")
print(f"Endpoint for subscription is: {endpoint}")

Ruby

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

# topic_id          = "your-topic-id"
# subscription_id   = "your-subscription-id"
# endpoint          = "https://your-test-project.appspot.com/push"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topic        = pubsub.topic topic_id
subscription = topic.subscribe subscription_id,
                               endpoint: endpoint

puts "Push subscription #{subscription_id} created."

使用订阅属性

您可以在创建或更新订阅时设置订阅属性。 如需详细了解如何使用 gcloud 命令行工具设置订阅属性,请参阅 gcloud pubsub subscriptions creategcloud pubsub subscriptions update 可选标志。

订阅具有以下属性:

属性 说明 默认
交付方式

您可以通过拉取推送传送方式接收消息。在拉取传送模式下,订阅者应用向 Pub/Sub 服务器发起请求来检索消息。在推送传送模式下,Pub/Sub 向订阅者应用发起请求来传送消息。

如果未指定,Pub/Sub 订阅使用拉取传送。

确认截止期限

如果您的代码在截止时间前没有确认消息,则系统会再次发送消息。

10 秒是默认的确认截止时间。最长为 10 分钟。

消息保留时长

消息保留时长指定 Pub/Sub 在发布后保留消息的时间。超过消息保留时长之后,Pub/Sub 可以随意舍弃消息,无论其确认状态为何。

如需保留已确认的消息,请参阅重放和舍弃消息

7 天是默认的消息保留时长。最小值为 10 分钟,最大值为 7 天。
死信主题

如果订阅者无法确认消息,则 Pub/Sub 可以将消息转发到死信主题。如需了解详情,请参阅转发到死信主题

如果您设置死信主题,则无法启用消息排序。

如果设置了死信主题,还可以指定传送尝试次数上限。默认为 5 次传送尝试;您可以将传送尝试次数指定在 5 至 100 次之间。

如果您设置了死信主题,并且该主题位于与订阅不同的项目中,那么您还必须指定具有死信主题的项目 ID。

有效期

如果没有订阅者活动(例如打开连接、主动拉取或成功推送),则订阅会过期。如果 Pub/Sub 检测到订阅者活动,则订阅删除时钟会重启。

默认有效期是 31 天。最小值为 1 天

要阻止订阅过期,请将有效期设置为 never

重试政策

如果确认截止时间到期或订阅者返回否定确认,则 Pub/Sub 可以使用指数退避算法发送消息。

如果未设置重试政策,Pub/Sub 会在确认截止时间到期或订阅者做出否定确认响应时重新发送消息。

如果设置了最大退避时间,则默认的最小退避时长为 10 秒。如果设置了最小退避时间,则默认最大退避时长为 600 秒。

可指定的最长退避时长为 600 秒。

消息排序

如果发布者使用排序键发送消息且已设置消息排序,则 Pub/Sub 会按顺序传送消息。

如果未设置消息排序,则 Pub/Sub 不会按顺序传送消息,包括具有排序键的消息。

过滤条件

过滤条件是包含过滤表达式的字符串。如果某个订阅具有过滤条件,则该订阅将仅传递与过滤条件匹配的消息。您可以按消息的属性过滤消息。

如果未指定,则订阅不会过滤消息,并且订阅者会收到所有消息。

使用重试政策

当订阅有重试政策,Pub/Sub 会在您指定的退避时限过后重新发送未确认的消息。Pub/Sub 会尽最大努力在退避时限后重新发送消息,因此消息可能会在最短退避时限前收到消息。

如果消息采用批处理,则在发生以下任一情况时,Pub/Sub 会启动指数退避算法:

  • 订阅者为批次中的每条消息发送否定确认。
  • 确认截止时间到期。

在退避时限过后,Pub/Sub 会重新提交该批次。

如果收到推送订阅消息,Pub/Sub 可能会在推送退避时限(而非指数退避时限)后传送消息。当推送退避时间超过指数退避时限时,Pub/Sub 会在推送退避后重新提交未确认的消息。

修改传送方式

您可以使用 Cloud Console、gcloud 命令行工具或 Pub/Sub API 在推送订阅和拉取订阅之间切换。

控制台

要修改推送订阅,请完成以下步骤。

  1. 在 Cloud Console 中,转到订阅页面。

    转到“订阅”页面

  2. 点击订阅旁边的 进行更新。

    突出显示“修改”选项的上下文菜单。

  3. 传送类型中,选择拉取推送
  4. 点击更新

gcloud

要修改推送端点网址,请运行 modify-push-config 命令:

gcloud pubsub subscriptions modify-push-config SUBSCRIPTION_ID \
    --push-endpoint=PUSH_ENDPOINT

如果订阅已使用拉取传送,则设置推送端点会将传送方式切换为推送传送。

您可以通过将推送端点更改为空字符串来将推送切换为拉取。

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& subscription_id, std::string const& endpoint) {
  auto status = client.ModifyPushSubscription(
      pubsub::Subscription(project_id, std::move(subscription_id)),
      pubsub::PushConfigBuilder{}.set_push_endpoint(endpoint));
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The subscription push configuration was successfully"
            << " modified\n";
}

C#

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


using Google.Cloud.PubSub.V1;

public class UpdatePushConfigurationSample
{
    public void UpdatePushConfiguration(string projectId, string subscriptionId, string pushEndpoint)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        PushConfig pushConfig = new PushConfig { PushEndpoint = pushEndpoint };

        subscriber.ModifyPushConfig(subscriptionName, pushConfig);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

func updateEndpoint(w io.Writer, projectID, subID string, endpoint string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	// 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: %v", err)
	}

	subConfig, err := client.Subscription(subID).Update(ctx, pubsub.SubscriptionConfigToUpdate{
		PushConfig: &pubsub.PushConfig{Endpoint: endpoint},
	})
	if err != nil {
		return fmt.Errorf("Update: %v", err)
	}
	fmt.Fprintf(w, "Updated subscription config: %v\n", subConfig)
	return nil
}

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

public class UpdatePushConfigurationExample {
  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 pushEndpoint = "https://my-test-project.appspot.com/push";

    updatePushConfigurationExample(projectId, subscriptionId, pushEndpoint);
  }

  public static void updatePushConfigurationExample(
      String projectId, String subscriptionId, String pushEndpoint) throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).build();
      subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
      Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
      System.out.println(
          "Updated push endpoint to: " + subscription.getPushConfig().getPushEndpoint());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

// 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 modifyPushConfig() {
  const options = {
    // Set to an HTTPS endpoint of your choice. If necessary, register
    // (authorize) the domain on which the server is hosted.
    pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`,
  };

  await pubSubClient
    .topic(topicName)
    .subscription(subscriptionName)
    .modifyPushConfig(options);
  console.log(`Modified push config for subscription ${subscriptionName}.`);
}

modifyPushConfig().catch(console.error);

Python

在尝试此示例之前,请按照《Pub/Sub 快速入门:使用客户端库》中的 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"

subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(project_id, subscription_id)

push_config = pubsub_v1.types.PushConfig(push_endpoint=endpoint)

subscription = pubsub_v1.types.Subscription(
    name=subscription_path, topic=topic_id, push_config=push_config
)

update_mask = {"paths": {"push_config"}}

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    result = subscriber.update_subscription(
        request={"subscription": subscription, "update_mask": update_mask}
    )

print(f"Subscription updated: {subscription_path}")
print(f"New endpoint for subscription is: {result.push_config}.")

Ruby

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

# subscription_id   = "your-subscription-id"
# new_endpoint      = "Endpoint where your app receives messages""
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

subscription          = pubsub.subscription subscription_id
subscription.endpoint = new_endpoint

puts "Push endpoint updated."

列出订阅

您可以使用 Cloud Console、gcloud 命令行工具或 Pub/Sub API 在 Google Cloud 项目中列出订阅。

控制台

要列出项目中的订阅,请转到订阅页面。

转到“订阅”页面

gcloud

要列出 Google Cloud 项目中的订阅,请运行 gcloud pubsub subscriptions list 命令:

gcloud pubsub subscriptions list [--project=PROJECT_ID]

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id) {
  int count = 0;
  for (auto const& subscription : client.ListSubscriptions(project_id)) {
    if (!subscription)
      throw std::runtime_error(subscription.status().message());
    std::cout << "Subscription Name: " << subscription->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No subscriptions found in project " << project_id << "\n";
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListSubscriptionsSample
{
    public IEnumerable<Subscription> ListSubscriptions(string projectId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        ProjectName projectName = ProjectName.FromProject(projectId);
        var subscriptions = subscriber.ListSubscriptions(projectName);
        return subscriptions;
    }
}

Go

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
)

func list(projectID string) ([]*pubsub.Subscription, error) {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	var subs []*pubsub.Subscription
	it := client.Subscriptions(ctx)
	for {
		s, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("Next: %v", err)
		}
		subs = append(subs, s)
	}
	return subs, nil
}

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

public class ListSubscriptionsInProjectExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";

    listSubscriptionInProjectExample(projectId);
  }

  public static void listSubscriptionInProjectExample(String projectId) throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectName projectName = ProjectName.of(projectId);
      for (Subscription subscription :
          subscriptionAdminClient.listSubscriptions(projectName).iterateAll()) {
        System.out.println(subscription.getName());
      }
      System.out.println("Listed all the subscriptions in the project.");
    }
  }
}

Node.js

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

// 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 listSubscriptions() {
  // Lists all subscriptions in the current project
  const [subscriptions] = await pubSubClient.getSubscriptions();
  console.log('Subscriptions:');
  subscriptions.forEach(subscription => console.log(subscription.name));
}

listSubscriptions().catch(console.error);

PHP

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

use Google\Cloud\PubSub\PubSubClient;

/**
 * Lists all Pub/Sub subscriptions.
 *
 * @param string $projectId  The Google project ID.
 */
function list_subscriptions($projectId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    foreach ($pubsub->subscriptions() as $subscription) {
        printf('Subscription: %s' . PHP_EOL, $subscription->name());
    }
}

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"

subscriber = pubsub_v1.SubscriberClient()
project_path = f"projects/{project_id}"

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    for subscription in subscriber.list_subscriptions(
        request={"project": project_path}
    ):
        print(subscription.name)

Ruby

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

require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

subscriptions = pubsub.list_subscriptions

puts "Subscriptions:"
subscriptions.each do |subscription|
  puts subscription.name
end

您可以使用 Cloud Console、gcloud 命令行工具或 Pub/Sub API 列出主题的订阅。

控制台

  1. 在 Cloud Console 中,转到主题页面。

    转到“主题”页面

  2. 选择主题 ID 以打开主题详细信息页面。页面的订阅部分包含对主题的订阅列表。

gcloud

要列出 Google Cloud 项目中的订阅,请运行 gcloud pubsub topics list-subscriptions 命令:

gcloud pubsub topics list-subscriptions TOPIC_ID

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string project_id,
   std::string topic_id) {
  auto const topic =
      pubsub::Topic(std::move(project_id), std::move(topic_id));
  std::cout << "Subscription list for topic " << topic << ":\n";
  for (auto const& name : client.ListTopicSubscriptions(topic)) {
    if (!name) throw std::runtime_error(name.status().message());
    std::cout << "  " << *name << "\n";
  }
}

C#

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


using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListSubscriptionsInTopicSample
{
    public IEnumerable<string> ListSubscriptionsInTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        IEnumerable<string> subscriptions = publisher.ListTopicSubscriptions(topicName);
        return subscriptions;
    }
}

Go

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
)

func listSubscriptions(projectID, topicID string) ([]*pubsub.Subscription, error) {
	// projectID := "my-project-id"
	// topicName := "projects/sample-248520/topics/ocr-go-test-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	var subs []*pubsub.Subscription

	it := client.Topic(topicID).Subscriptions(ctx)
	for {
		sub, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("Next: %v", err)
		}
		subs = append(subs, sub)
	}
	return subs, nil
}

Java

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


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class ListSubscriptionsInTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    listSubscriptionInTopicExample(projectId, topicId);
  }

  public static void listSubscriptionInTopicExample(String projectId, String topicId)
      throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      for (String subscription : topicAdminClient.listTopicSubscriptions(topicName).iterateAll()) {
        System.out.println(subscription);
      }
      System.out.println("Listed all the subscriptions in the topic.");
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

// 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 listTopicSubscriptions() {
  // Lists all subscriptions for the topic
  const [subscriptions] = await pubSubClient
    .topic(topicName)
    .getSubscriptions();

  console.log(`Subscriptions for ${topicName}:`);
  subscriptions.forEach(subscription => console.log(subscription.name));
}

listTopicSubscriptions().catch(console.error);

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)

response = publisher.list_topic_subscriptions(request={"topic": topic_path})
for subscription in response:
    print(subscription)

Ruby

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

# topic_id = "your-topic-id"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topic         = pubsub.topic topic_id
subscriptions = topic.subscriptions

puts "Subscriptions in topic #{topic.name}:"
subscriptions.each do |subscription|
  puts subscription.name
end

删除订阅

您可以使用 Cloud Console、gcloud 命令行工具或 Pub/Sub API 删除订阅。

控制台

  1. 在 Cloud Console 中,转到订阅页面。

    转到“订阅”页面

  2. 选择要删除的订阅。
  3. 点击删除

gcloud

要删除订阅,请运行 gcloud pubsub subscriptions delete 命令:

gcloud pubsub subscriptions delete SUBSCRIPTION_ID

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& subscription_id) {
  auto status = client.DeleteSubscription(pubsub::Subscription(
      std::move(project_id), std::move(subscription_id)));
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The subscription was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The subscription was successfully deleted\n";
}

C#

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


using Google.Cloud.PubSub.V1;

public class DeleteSubscriptionSample
{
    public void DeleteSubscription(string projectId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        subscriber.DeleteSubscription(subscriptionName);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

func delete(w io.Writer, projectID, subID string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	sub := client.Subscription(subID)
	if err := sub.Delete(ctx); err != nil {
		return fmt.Errorf("Delete: %v", err)
	}
	fmt.Fprintf(w, "Subscription %q deleted.", subID)
	return nil
}

Java

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


import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;

public class DeleteSubscriptionExample {

  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";

    deleteSubscriptionExample(projectId, subscriptionId);
  }

  public static void deleteSubscriptionExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      try {
        subscriptionAdminClient.deleteSubscription(subscriptionName);
        System.out.println("Deleted subscription.");
      } catch (NotFoundException e) {
        System.out.println(e.getMessage());
      }
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

// 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 deleteSubscription() {
  // Deletes the subscription
  await pubSubClient.subscription(subscriptionName).delete();
  console.log(`Subscription ${subscriptionName} deleted.`);
}

deleteSubscription().catch(console.error);

PHP

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

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function delete_subscription($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $subscription->delete();

    printf('Subscription deleted: %s' . PHP_EOL, $subscription->name());
}

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

subscriber = pubsub_v1.SubscriberClient()
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:
    subscriber.delete_subscription(request={"subscription": subscription_path})

print(f"Subscription deleted: {subscription_path}.")

Ruby

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

# subscription_id = "your-subscription-id"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
subscription.delete

puts "Subscription #{subscription_id} deleted."

资源名称

Pub/Sub 资源名称唯一标识 Pub/Sub 资源(例如订阅或主题),并且必须符合以下格式:

projects/project-identifier/collection/relative-name

project-identifier 必须是从 Google Cloud Console 获得的项目 ID。例如 projects/myproject/topics/mytopic

collection 必须是 subscriptionstopics

resource-name 必须满足以下条件:

  • 不以字符串 goog 开头。
  • 以字母开头
  • 包含 3 到 255 个字符
  • 仅包含以下字符:

    • 字母:[A-Za-z]
    • 数字:[0-9]
    • 短划线:-
    • 下划线:_
    • 英文句点:.
    • 波形符:~
    • 加号:+
    • 百分号:%

      上述列表中的特殊字符可用于没有网址编码的资源名称。不过,在网址中使用任何其他特殊字符时,您必须确保对这些字符正确进行编码/解码。例如,mi-tópico 是无效的 relative-name,而 mi-t%C3%B3pico 是有效的。

      这对于 REST 调用尤为重要。