创建和管理精简版订阅

订阅者使用精简版订阅从精简版主题中读取消息。创建精简版订阅时,您可以将其附加到精简版主题。您可以将多个精简版订阅附加到单个精简版主题。

订阅有两种类型:

  • 标准版订阅。当您的客户端需要从精简版主题中读取消息时,请创建标准订阅。
  • 导出订阅。如果您需要将精简版消息导出到 Pub/Sub,请创建导出订阅。如需了解详情,请参阅将 Pub/Sub Lite 消息导出到 Pub/Sub

精简版订阅的属性

可用区级精简版主题的订阅与区域级精简版主题订阅具有相同的属性,但存在以下属性:

  • 资源名称中使用的位置类型,可用区或区域。例如,区域位置是 us-central1;可用区位置的一个示例是 us-central1-a

  • 可靠性。如需详细了解区域主题和可用区级主题之间的可靠性差异,请参阅精简版主题中的数据复制

消息传送要求

将消息写入存储空间的临时失败会导致发布者尝试重新发送消息。这些重试对最终用户是透明的。精简版订阅具有传送要求属性,该属性会更改订阅对这些消息重试的反应方式。您可以将此属性设置为以下两个选项之一:

  • 立即传送消息。启用此选项后,订阅者客户端会在所有消息到达服务器后接收消息。此过程与写入磁盘的消息的状态无关。偏移不会重复使用,但在执行搜索操作后,具有未写入存储空间的偏移的消息可能无法重新读取。

  • 存储后传送消息。启用此选项后,订阅者在消息写入磁盘之前不会收到消息。还原操作后,可以重新读取这些消息。启用此选项会增加从发布者向订阅者接收消息的端到端延迟时间。

订阅命名准则

Pub/Sub Lite 资源名称唯一标识 Pub/Sub Lite 资源,例如主题、订阅或预留。资源名称必须符合以下格式:

projects/project-identifier/collection/ID

  • project-identifier:必须是可从 Google Cloud 控制台获得的项目 ID 或项目编号。例如,my-cool-project 是项目 ID。 123456789123 是项目编号。

  • collection:必须是 topicssubscriptionsreservations 中的一个。

  • ID:必须符合以下准则:

    • 不以字符串 goog 开头
    • 以字母开头
    • 包含 3 到 255 个字符
    • 只能包含以下字符:字母 [A-Za-z]、数字 [0-9]、短划线 -、下划线 _、句点 .、波浪线 ~、加号 + 和百分号 %

    您可以在不进行网址编码的资源名称中使用上述列表中的特殊字符。不过,在网址中使用任何其他特殊字符时,您必须确保已正确编码或解码这些字符。例如,mi-tópico 就是无效的 ID。不过,mi-t%C3%B3pico 是有效的。当您进行 REST 调用时,此格式很重要。

创建精简版订阅

精简版订阅必须与精简版订阅连接到的精简版主题位于同一项目和位置中。

如需创建精简版主题,请参阅创建和管理精简版主题

如需查看可用位置的列表,请参阅 Pub/Sub 精简版位置

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Pub/Sub Lite API 创建精简版订阅。

如需了解如何创建导出订阅,请参阅将 Pub/Sub Lite 消息导出到 Pub/Sub

控制台

  1. 前往精简版订阅页面。

    前往“精简版订阅”

  2. 点击创建精简版订阅

  3. 输入精简版订阅 ID

  4. 选择要接收消息的精简版主题。

  5. 选择立即传送消息在存储后传送消息

  6. 选择一种起始偏移量

  7. 选择传送类型

  8. 点击创建

gcloud

如需创建精简版订阅,请使用 gcloud pubsub lite-subscriptions create 命令:

gcloud pubsub lite-subscriptions create SUBSCRIPTION_ID \
  --location=LOCATION \
  --topic=TOPIC_ID \
  --delivery-requirement=DELIVERY_REQUIREMENT

替换以下内容:

  • SUBSCRIPTION_ID:精简版订阅的 ID

  • LOCATIONPub/Sub 精简版支持的位置的名称

  • TOPIC_ID:要附加到精简版订阅的精简版主题的 ID

  • DELIVERY_REQUIREMENTdeliver-after-storeddeliver-immediately

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

Created [SUBSCRIPTION_ID].

协议

要创建精简版订阅,请发送 POST 请求,如下所示:

POST https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

替换以下内容:

  • REGION:要在其中存储精简版订阅的区域

  • PROJECT_NUMBER:要在其中创建精简版订阅的项目的项目编号

  • LOCATIONPub/Sub 精简版支持的位置的名称

  • SUBSCRIPTION_ID:精简版订阅的 ID

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

{
  "topic": projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID,
  "deliveryConfig": {
    "deliveryRequirement": DELIVERY_REQUIREMENT,
   }
}

DELIVERY_REQUIREMENT 替换为 deliver-after-storeddeliver-immediately

如果请求成功,则响应是 JSON 格式的精简版订阅:

{
  "deliveryConfig": {
    "deliveryRequirement": DELIVERY_REQUIREMENT,
   }
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID",
  "topic": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
}

Go

运行此示例之前,请按照 Pub/Sub 精简版客户端库中的 Go 设置说明进行操作。

import (
	"context"
	"fmt"
	"io"

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

func createSubscription(w io.Writer, projectID, region, location, topicID, subID string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
	// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
	// location := "us-central1"
	// NOTE: topic and subscription must be in the same region/zone (e.g. "us-central1-a")
	// topicID := "my-topic"
	// subID := "my-subscription"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	sub, err := client.CreateSubscription(ctx, pubsublite.SubscriptionConfig{
		Name:                fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s", projectID, location, subID),
		Topic:               fmt.Sprintf("projects/%s/locations/%s/topics/%s", projectID, location, topicID),
		DeliveryRequirement: pubsublite.DeliverImmediately, // can also be DeliverAfterStored
	})
	if err != nil {
		return fmt.Errorf("client.CreateSubscription got err: %w", err)
	}
	fmt.Fprintf(w, "Created subscription: %s\n", sub.Name)
	return nil
}

Java

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Java 设置说明进行操作。

import com.google.api.gax.rpc.AlreadyExistsException;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.SubscriptionName;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.TopicName;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.proto.Subscription;
import com.google.cloud.pubsublite.proto.Subscription.DeliveryConfig;
import com.google.cloud.pubsublite.proto.Subscription.DeliveryConfig.DeliveryRequirement;
import java.util.concurrent.ExecutionException;

public class CreateSubscriptionExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String cloudRegion = "your-cloud-region";
    char zoneId = 'b';
    String topicId = "your-topic-id";
    String subscriptionId = "your-subscription-id";
    long projectNumber = Long.parseLong("123456789");
    // True if using a regional location. False if using a zonal location.
    // https://cloud.google.com/pubsub/lite/docs/topics
    boolean regional = false;

    createSubscriptionExample(
        cloudRegion, zoneId, projectNumber, topicId, subscriptionId, regional);
  }

  public static void createSubscriptionExample(
      String cloudRegion,
      char zoneId,
      long projectNumber,
      String topicId,
      String subscriptionId,
      boolean regional)
      throws Exception {

    CloudRegionOrZone location;
    if (regional) {
      location = CloudRegionOrZone.of(CloudRegion.of(cloudRegion));
    } else {
      location = CloudRegionOrZone.of(CloudZone.of(CloudRegion.of(cloudRegion), zoneId));
    }

    TopicPath topicPath =
        TopicPath.newBuilder()
            .setProject(ProjectNumber.of(projectNumber))
            .setLocation(location)
            .setName(TopicName.of(topicId))
            .build();

    SubscriptionPath subscriptionPath =
        SubscriptionPath.newBuilder()
            .setLocation(location)
            .setProject(ProjectNumber.of(projectNumber))
            .setName(SubscriptionName.of(subscriptionId))
            .build();

    Subscription subscription =
        Subscription.newBuilder()
            .setDeliveryConfig(
                // Possible values for DeliveryRequirement:
                // - `DELIVER_IMMEDIATELY`
                // - `DELIVER_AFTER_STORED`
                // You may choose whether to wait for a published message to be successfully written
                // to storage before the server delivers it to subscribers. `DELIVER_IMMEDIATELY` is
                // suitable for applications that need higher throughput.
                DeliveryConfig.newBuilder()
                    .setDeliveryRequirement(DeliveryRequirement.DELIVER_IMMEDIATELY))
            .setName(subscriptionPath.toString())
            .setTopic(topicPath.toString())
            .build();

    AdminClientSettings adminClientSettings =
        AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Subscription response = adminClient.createSubscription(subscription).get();
      System.out.println(response.getAllFields() + " created successfully.");
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (AlreadyExistsException alreadyExists) {
        System.out.println("This subscription already exists.");
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
  }
}

Python

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Python 设置说明进行操作。

from google.api_core.exceptions import AlreadyExists
from google.cloud.pubsublite import AdminClient, Subscription
from google.cloud.pubsublite.types import (
    CloudRegion,
    CloudZone,
    SubscriptionPath,
    TopicPath,
)

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# regional = True

if regional:
    location = CloudRegion(cloud_region)
else:
    location = CloudZone(CloudRegion(cloud_region), zone_id)

topic_path = TopicPath(project_number, location, topic_id)
subscription_path = SubscriptionPath(project_number, location, subscription_id)

subscription = Subscription(
    name=str(subscription_path),
    topic=str(topic_path),
    delivery_config=Subscription.DeliveryConfig(
        # Possible values for delivery_requirement:
        # - `DELIVER_IMMEDIATELY`
        # - `DELIVER_AFTER_STORED`
        # You may choose whether to wait for a published message to be successfully written
        # to storage before the server delivers it to subscribers. `DELIVER_IMMEDIATELY` is
        # suitable for applications that need higher throughput.
        delivery_requirement=Subscription.DeliveryConfig.DeliveryRequirement.DELIVER_IMMEDIATELY,
    ),
)

client = AdminClient(cloud_region)
try:
    response = client.create_subscription(subscription)
    print(f"{response.name} created successfully.")
except AlreadyExists:
    print(f"{subscription_path} already exists.")

创建精简版订阅后,您可以从精简版订阅接收消息

更新精简版订阅

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Pub/Sub Lite API 更新精简版订阅。

控制台

  1. 前往精简版订阅页面。

    前往“精简版订阅”

  2. 点击精简版订阅 ID。

  3. 精简版订阅详情页面中,点击修改

gcloud

要更新精简版订阅,请使用 gcloud pubsub lite-subscriptions update 命令:

gcloud pubsub lite-subscriptions update SUBSCRIPTION_ID \
  --location=LOCATION \
  --delivery-requirement=DELIVERY_REQUIREMENT

替换以下内容:

  • SUBSCRIPTION_ID:精简版订阅的 ID

  • LOCATION:精简版订阅所在的位置名称

  • DELIVERY_REQUIREMENTdeliver-after-storeddeliver-immediately

如果请求成功,命令行将显示精简版订阅:

deliveryConfig:
  deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

协议

要更新精简版订阅,请发送 PATCH 请求,如下所示:

PATCH https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID?updateMask=deliveryConfig.deliveryRequirement
Authorization: Bearer $(gcloud auth print-access-token)

替换以下内容:

  • REGION:要在其中存储精简版订阅的区域

  • PROJECT_NUMBER:具有精简版订阅的项目的项目编号

  • LOCATION:精简版订阅所在的位置名称

  • SUBSCRIPTION_ID:精简版订阅的 ID

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

{
  "deliveryConfig": {
    "deliveryRequirement": DELIVERY_REQUIREMENT,
   }
}

DELIVERY_REQUIREMENT 替换为 deliver-after-storeddeliver-immediately

如果请求成功,则响应是 JSON 格式的精简版订阅:

{
  "deliveryConfig": {
    "deliveryRequirement": DELIVERY_REQUIREMENT,
   }
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID",
  "topic": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
}

Go

运行此示例之前,请按照 Pub/Sub 精简版客户端库中的 Go 设置说明进行操作。

import (
	"context"
	"fmt"
	"io"

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

func updateSubscription(w io.Writer, projectID, region, location, subID string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
	// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
	// location := "us-central1"
	// subID := "my-subscription"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	subPath := fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s", projectID, location, subID)
	config := pubsublite.SubscriptionConfigToUpdate{
		Name:                subPath,
		DeliveryRequirement: pubsublite.DeliverAfterStored,
	}
	updatedCfg, err := client.UpdateSubscription(ctx, config)
	if err != nil {
		return fmt.Errorf("client.UpdateSubscription got err: %w", err)
	}
	fmt.Fprintf(w, "Updated subscription: %#v\n", updatedCfg)
	return nil
}

Java

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Java 设置说明进行操作。

import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.SubscriptionName;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.proto.Subscription;
import com.google.cloud.pubsublite.proto.Subscription.DeliveryConfig;
import com.google.cloud.pubsublite.proto.Subscription.DeliveryConfig.DeliveryRequirement;
import com.google.protobuf.FieldMask;
import java.util.concurrent.ExecutionException;

public class UpdateSubscriptionExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String cloudRegion = "your-cloud-region";
    char zoneId = 'b';
    // Choose an existing subscription.
    String subscriptionId = "your-subscription-id";
    long projectNumber = Long.parseLong("123456789");
    // True if using a regional location. False if using a zonal location.
    // https://cloud.google.com/pubsub/lite/docs/topics
    boolean regional = false;

    updateSubscriptionExample(cloudRegion, zoneId, projectNumber, subscriptionId, regional);
  }

  public static void updateSubscriptionExample(
      String cloudRegion, char zoneId, long projectNumber, String subscriptionId, boolean regional)
      throws Exception {

    CloudRegionOrZone location;
    if (regional) {
      location = CloudRegionOrZone.of(CloudRegion.of(cloudRegion));
    } else {
      location = CloudRegionOrZone.of(CloudZone.of(CloudRegion.of(cloudRegion), zoneId));
    }

    SubscriptionPath subscriptionPath =
        SubscriptionPath.newBuilder()
            .setLocation(location)
            .setProject(ProjectNumber.of(projectNumber))
            .setName(SubscriptionName.of(subscriptionId))
            .build();

    FieldMask fieldMask =
        FieldMask.newBuilder().addPaths("delivery_config.delivery_requirement").build();

    Subscription subscription =
        Subscription.newBuilder()
            .setDeliveryConfig(
                // Possible values for DeliveryRequirement:
                // - `DELIVER_IMMEDIATELY`
                // - `DELIVER_AFTER_STORED`
                // `DELIVER_AFTER_STORED` requires a published message to be successfully written
                // to storage before the server delivers it to subscribers.
                DeliveryConfig.newBuilder()
                    .setDeliveryRequirement(DeliveryRequirement.DELIVER_AFTER_STORED))
            .setName(subscriptionPath.toString())
            .build();

    AdminClientSettings adminClientSettings =
        AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Subscription subscriptionBeforeUpdate = adminClient.getSubscription(subscriptionPath).get();
      System.out.println("Before update: " + subscriptionBeforeUpdate.getAllFields());

      Subscription subscriptionAfterUpdate =
          adminClient.updateSubscription(subscription, fieldMask).get();
      System.out.println("After update: " + subscriptionAfterUpdate.getAllFields());
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This subscription is not found.");
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
  }
}

Python

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Python 设置说明进行操作。

from google.api_core.exceptions import NotFound
from google.cloud.pubsublite import AdminClient, Subscription
from google.cloud.pubsublite.types import CloudRegion, CloudZone, SubscriptionPath
from google.protobuf.field_mask_pb2 import FieldMask

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# regional = True

if regional:
    location = CloudRegion(cloud_region)
else:
    location = CloudZone(CloudRegion(cloud_region), zone_id)

subscription_path = SubscriptionPath(project_number, location, subscription_id)
field_mask = FieldMask(paths=["delivery_config.delivery_requirement"])

subscription = Subscription(
    name=str(subscription_path),
    delivery_config=Subscription.DeliveryConfig(
        # Possible values for delivery_requirement:
        # - `DELIVER_IMMEDIATELY`
        # - `DELIVER_AFTER_STORED`
        # `DELIVER_AFTER_STORED` requires a published message to be successfully written
        # to storage before the server delivers it to subscribers.
        delivery_requirement=Subscription.DeliveryConfig.DeliveryRequirement.DELIVER_AFTER_STORED,
    ),
)

client = AdminClient(cloud_region)
try:
    response = client.update_subscription(subscription, field_mask)
    print(f"{response.name} updated successfully.")
except NotFound:
    print(f"{subscription_path} not found.")

查看精简版订阅详情

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Pub/Sub Lite API 获取有关精简版订阅的详细信息。

控制台

  1. 前往精简版订阅页面。

    前往“精简版订阅”

  2. 点击精简版订阅 ID。

  3. 在精简版订阅详情页面中,点击详细信息标签页。

gcloud

要获取有关精简版订阅的详细信息,请使用 gcloud pubsub lite-subscriptions describe 命令:

gcloud pubsub lite-subscriptions describe SUBSCRIPTION_ID \
  --location=LOCATION

替换以下内容:

  • SUBSCRIPTION_ID:精简版订阅的 ID

  • LOCATION:精简版订阅所在的位置名称

如果请求成功,命令行将显示精简版主题:

deliveryConfig:
  deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

协议

如需获取有关精简版订阅的详细信息,请发送 GET 请求,如下所示:

GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

替换以下内容:

  • REGION:要在其中存储精简版订阅的区域

  • PROJECT_NUMBER:具有精简版订阅的项目的项目编号

  • LOCATION:精简版订阅所在的位置名称

  • SUBSCRIPTION_ID:精简版订阅的 ID

如果请求成功,则响应是 JSON 格式的精简版主题:

{
  "deliveryConfig": {
    "deliveryRequirement": DELIVERY_REQUIREMENT,
   }
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID",
  "topic": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
}

Go

运行此示例之前,请按照 Pub/Sub 精简版客户端库中的 Go 设置说明进行操作。

import (
	"context"
	"fmt"
	"io"

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

func getSubscription(w io.Writer, projectID, region, location, subID string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
	// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
	// location := "us-central1"
	// subID := "my-subscription"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	subPath := fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s", projectID, location, subID)
	sub, err := client.Subscription(ctx, subPath)
	if err != nil {
		return fmt.Errorf("client.Subscription got err: %w", err)
	}
	fmt.Fprintf(w, "Got subscription: %#v\n", sub)
	return nil
}

Java

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Java 设置说明进行操作。

import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.SubscriptionName;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.proto.Subscription;
import java.util.concurrent.ExecutionException;

public class GetSubscriptionExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String cloudRegion = "your-cloud-region";
    char zoneId = 'b';
    // Choose an existing subscription.
    String subscriptionId = "your-subscription-id";
    long projectNumber = Long.parseLong("123456789");
    // True if using a regional location. False if using a zonal location.
    // https://cloud.google.com/pubsub/lite/docs/topics
    boolean regional = false;

    getSubscriptionExample(cloudRegion, zoneId, projectNumber, subscriptionId, regional);
  }

  public static void getSubscriptionExample(
      String cloudRegion, char zoneId, long projectNumber, String subscriptionId, boolean regional)
      throws Exception {

    CloudRegionOrZone location;
    if (regional) {
      location = CloudRegionOrZone.of(CloudRegion.of(cloudRegion));
    } else {
      location = CloudRegionOrZone.of(CloudZone.of(CloudRegion.of(cloudRegion), zoneId));
    }

    SubscriptionPath subscriptionPath =
        SubscriptionPath.newBuilder()
            .setLocation(location)
            .setProject(ProjectNumber.of(projectNumber))
            .setName(SubscriptionName.of(subscriptionId))
            .build();

    AdminClientSettings adminClientSettings =
        AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Subscription subscription = adminClient.getSubscription(subscriptionPath).get();
      System.out.println(subscription.getAllFields());
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This subscription is not found.");
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
  }
}

Python

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Python 设置说明进行操作。

from google.api_core.exceptions import NotFound
from google.cloud.pubsublite import AdminClient
from google.cloud.pubsublite.types import CloudRegion, CloudZone, SubscriptionPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# subscription_id = "your-subscription-id"
# regional = True

if regional:
    location = CloudRegion(cloud_region)
else:
    location = CloudZone(CloudRegion(cloud_region), zone_id)

subscription_path = SubscriptionPath(project_number, location, subscription_id)

client = AdminClient(cloud_region)
try:
    response = client.get_subscription(subscription_path)
    print(f"{response.name} exists.")
except NotFound:
    print(f"{subscription_path} not found.")

列出精简版订阅

您可以列出项目中的精简订阅精简版主题的精简版订阅

列出项目中的精简版订阅

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Pub/Sub Lite API 列出项目中的精简版订阅。

控制台

gcloud

gcloud pubsub lite-subscriptions list \
  --location=LOCATION

LOCATION 替换为精简版订阅的位置名称。

如果请求成功,命令行将显示精简版订阅:

---
deliveryConfig:
  deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
---
deliveryConfig:
  deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

协议

  • 如需列出项目中的精简版订阅,请发送 GET 请求,如下所示:
GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/subscriptions
Authorization: Bearer $(gcloud auth print-access-token)

替换以下内容:

  • REGION:要在其中存储精简版订阅的区域

  • PROJECT_NUMBER:具有精简版订阅的项目的项目编号

如果请求成功,则响应是 JSON 格式的精简版主题:

{
  "subscriptions": [
      {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
      },
      {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
      }
  ]
}

Go

运行此示例之前,请按照 Pub/Sub 精简版客户端库中的 Go 设置说明进行操作。

import (
	"context"
	"fmt"
	"io"

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

func listSubscriptionsInProject(w io.Writer, projectID, region, location string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
	// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
	// location := "us-central1"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	// To list topics in a region, set location to a cloud region instead.
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, location)
	subIter := client.Subscriptions(ctx, parent)
	for {
		sub, err := subIter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("subIter.Next() got err: %w", err)
		}
		fmt.Fprintf(w, "Got subscription config: %v", sub)
	}
	return nil
}

Java

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Java 设置说明进行操作。

import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.LocationPath;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.proto.Subscription;
import java.util.List;

public class ListSubscriptionsInProjectExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String cloudRegion = "your-cloud-region";
    char zoneId = 'b';
    long projectNumber = Long.parseLong("123456789");
    // True if using a regional location. False if using a zonal location.
    // https://cloud.google.com/pubsub/lite/docs/topics
    boolean regional = true;

    listSubscriptionsInProjectExample(cloudRegion, zoneId, projectNumber, regional);
  }

  public static void listSubscriptionsInProjectExample(
      String cloudRegion, char zoneId, long projectNumber, boolean regional) throws Exception {

    AdminClientSettings adminClientSettings =
        AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();

    CloudRegionOrZone location;
    if (regional) {
      location = CloudRegionOrZone.of(CloudRegion.of(cloudRegion));
    } else {
      location = CloudRegionOrZone.of(CloudZone.of(CloudRegion.of(cloudRegion), zoneId));
    }

    LocationPath locationPath =
        LocationPath.newBuilder()
            .setProject(ProjectNumber.of(projectNumber))
            .setLocation(location)
            .build();

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      List<Subscription> subscriptions = adminClient.listSubscriptions(locationPath).get();
      for (Subscription subscription : subscriptions) {
        System.out.println(subscription.getAllFields());
      }
      System.out.println(subscriptions.size() + " subscription(s) listed in the project.");
    }
  }
}

Python

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Python 设置说明进行操作。

from google.cloud.pubsublite import AdminClient
from google.cloud.pubsublite.types import CloudRegion, CloudZone, LocationPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# regional = True

if regional:
    location = CloudRegion(cloud_region)
else:
    location = CloudZone(CloudRegion(cloud_region), zone_id)

location_path = LocationPath(project_number, location)

client = AdminClient(cloud_region)
response = client.list_subscriptions(location_path)

for subscription in response:
    print(subscription.name)

print(f"{len(response)} subscription(s) listed in your project and location.")

列出精简版主题的精简版订阅

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Pub/Sub Lite API 列出精简版主题的精简版订阅。

控制台

  1. 前往精简版主题页面。

    前往精简版主题

  2. 选择精简版主题 ID。

  3. 精简版主题详情页面中,精简版订阅部分包含精简版主题的一系列订阅。

gcloud

gcloud pubsub lite-topics list-subscriptions TOPIC_ID \
  --location=LOCATION

替换以下内容:

  • TOPIC_ID:附加精简版订阅的精简版主题的 ID

  • LOCATION:精简版订阅所在的位置名称

如果请求成功,命令行将显示精简版订阅:

---
deliveryConfig:
  deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
---
deliveryConfig:
  deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

协议

  • 要列出精简版主题的精简版订阅,请按如下所示发送 GET 请求:
GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/lite-topics/TOPIC_ID/subscriptions
Authorization: Bearer $(gcloud auth print-access-token)

替换以下内容:

  • REGION:要在其中存储精简版订阅的区域

  • PROJECT_NUMBER:具有精简版订阅的项目的项目编号

  • LOCATION:精简版订阅所在的位置名称

  • TOPIC_ID:附加精简版订阅的精简版主题的 ID

如果请求成功,则响应是以 JSON 格式列出的精简版订阅列表:

{
  "subscriptions": [
      {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
      },
      {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
      }
  ]
}

Go

运行此示例之前,请按照 Pub/Sub 精简版客户端库中的 Go 设置说明进行操作。

import (
	"context"
	"fmt"
	"io"

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

func listSubscriptionsInTopic(w io.Writer, projectID, region, location, topicID string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
	// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
	// location := "us-central"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	topicPath := fmt.Sprintf("projects/%s/locations/%s/topics/%s", projectID, location, topicID)
	subPathIter := client.TopicSubscriptions(ctx, topicPath)
	for {
		subPath, err := subPathIter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("subPathIter.Next got err: %w", err)
		}
		fmt.Fprintf(w, "Got subscription: %s\n", subPath)
	}
	return nil
}

Java

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Java 设置说明进行操作。

import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.TopicName;
import com.google.cloud.pubsublite.TopicPath;
import java.util.List;

public class ListSubscriptionsInTopicExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String cloudRegion = "your-cloud-region";
    char zoneId = 'b';
    long projectNumber = Long.parseLong("123456789");
    String topicId = "your-topic-id";
    // True if using a regional location. False if using a zonal location.
    // https://cloud.google.com/pubsub/lite/docs/topics
    boolean regional = false;

    listSubscriptionsInTopicExample(cloudRegion, zoneId, projectNumber, topicId, regional);
  }

  public static void listSubscriptionsInTopicExample(
      String cloudRegion, char zoneId, long projectNumber, String topicId, boolean regional)
      throws Exception {

    CloudRegionOrZone location;
    if (regional) {
      location = CloudRegionOrZone.of(CloudRegion.of(cloudRegion));
    } else {
      location = CloudRegionOrZone.of(CloudZone.of(CloudRegion.of(cloudRegion), zoneId));
    }

    TopicPath topicPath =
        TopicPath.newBuilder()
            .setProject(ProjectNumber.of(projectNumber))
            .setLocation(location)
            .setName(TopicName.of(topicId))
            .build();

    AdminClientSettings adminClientSettings =
        AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      List<SubscriptionPath> subscriptionPaths =
          adminClient.listTopicSubscriptions(topicPath).get();
      for (SubscriptionPath subscription : subscriptionPaths) {
        System.out.println(subscription.toString());
      }
      if (regional) {
        System.out.println(
            subscriptionPaths.size()
                + " subscription(s) listed in the regional topic "
                + topicPath);
      } else {
        System.out.println(
            subscriptionPaths.size() + " subscription(s) listed in the zonal topic " + topicPath);
      }
    }
  }
}

Python

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Python 设置说明进行操作。

from google.cloud.pubsublite import AdminClient
from google.cloud.pubsublite.types import CloudRegion, CloudZone, TopicPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# topic_id = "your-topic-id"
# regional = True

if regional:
    location = CloudRegion(cloud_region)
else:
    location = CloudZone(CloudRegion(cloud_region), zone_id)

topic_path = TopicPath(project_number, location, topic_id)

client = AdminClient(cloud_region)
response = client.list_topic_subscriptions(topic_path)

for subscription_path in response:
    print(subscription_path)

print(f"{len(response)} subscription(s) listed in your topic.")

删除精简版订阅

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Pub/Sub Lite API 删除精简版订阅。

控制台

  1. 前往精简版订阅页面。

    前往“精简版订阅”

  2. 点击精简版订阅 ID。

  3. 精简版订阅详情页面中,点击删除

  4. 在显示的对话框中,点击删除以确认您要删除精简版订阅。

gcloud

要删除精简版订阅,请使用 gcloud pubsub lite-subscriptions delete 命令:

  1. 运行 delete 命令:

    gcloud pubsub lite-subscriptions delete SUBSCRIPTION_ID \
     --location=LOCATION
    

    替换以下内容:

    • SUBSCRIPTION_ID:精简版订阅的 ID

    • LOCATION:精简版订阅所在的位置名称

  2. 如需确认,请输入 Y

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

Deleted subscription [SUBSCRIPTION_ID].

协议

  • 要删除精简版主题,请发送 DELETE 请求,如下所示:
DELETE https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

替换以下内容:

  • REGION:要在其中存储精简版订阅的区域

  • PROJECT_NUMBER:具有精简版订阅的项目的项目编号

  • LOCATION:精简版订阅所在的位置名称

  • SUBSCRIPTION_ID:精简版订阅的 ID

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

Go

运行此示例之前,请按照 Pub/Sub 精简版客户端库中的 Go 设置说明进行操作。

import (
	"context"
	"fmt"
	"io"

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

func deleteSubscription(w io.Writer, projectID, region, location, subID string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
	// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
	// location := "us-central1"
	// subID := "my-subscription"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	err = client.DeleteSubscription(ctx, fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s", projectID, location, subID))
	if err != nil {
		return fmt.Errorf("client.DeleteSubscription got err: %w", err)
	}
	fmt.Fprintf(w, "Deleted subscription\n")
	return nil
}

Java

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Java 设置说明进行操作。

import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.SubscriptionName;
import com.google.cloud.pubsublite.SubscriptionPath;
import java.util.concurrent.ExecutionException;

public class DeleteSubscriptionExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String cloudRegion = "your-cloud-region";
    char zoneId = 'b';
    // Choose an existing subscription.
    String subscriptionId = "your-subscription-id";
    long projectNumber = Long.parseLong("123456789");
    // True if using a regional location. False if using a zonal location.
    // https://cloud.google.com/pubsub/lite/docs/topics
    boolean regional = false;

    deleteSubscriptionExample(cloudRegion, zoneId, projectNumber, subscriptionId, regional);
  }

  public static void deleteSubscriptionExample(
      String cloudRegion, char zoneId, long projectNumber, String subscriptionId, boolean regional)
      throws Exception {

    CloudRegionOrZone location;
    if (regional) {
      location = CloudRegionOrZone.of(CloudRegion.of(cloudRegion));
    } else {
      location = CloudRegionOrZone.of(CloudZone.of(CloudRegion.of(cloudRegion), zoneId));
    }

    SubscriptionPath subscriptionPath =
        SubscriptionPath.newBuilder()
            .setLocation(location)
            .setProject(ProjectNumber.of(projectNumber))
            .setName(SubscriptionName.of(subscriptionId))
            .build();

    AdminClientSettings adminClientSettings =
        AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      adminClient.deleteSubscription(subscriptionPath).get();
      System.out.println(subscriptionPath + " deleted successfully.");
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This subscription is not found.");
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
  }
}

Python

在运行此示例之前,请按照 Pub/Sub Lite 客户端库中的 Python 设置说明进行操作。

from google.api_core.exceptions import NotFound
from google.cloud.pubsublite import AdminClient
from google.cloud.pubsublite.types import CloudRegion, CloudZone, SubscriptionPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# subscription_id = "your-subscription-id"
# regional = True

if regional:
    location = CloudRegion(cloud_region)
else:
    location = CloudZone(CloudRegion(cloud_region), zone_id)

subscription_path = SubscriptionPath(project_number, location, subscription_id)

client = AdminClient(cloud_region)
try:
    client.delete_subscription(subscription_path)
    print(f"{subscription_path} deleted successfully.")
except NotFound:
    print(f"{subscription_path} not found.")

后续步骤