创建和管理精简版预留

本文档介绍了如何使用和管理 Pub/Sub Lite 预留。本文档还介绍了容量单位的概念,以及如何 确定适应应用吞吐量所需的大小。

精简版预留概览

精简版预留预配并在一个服务之间动态共享吞吐量容量 一个或多个精简版主题。这些主题可能是区域级或可用区级精简版 主题。与设置吞吐量相比,使用精简版预留是更好的选择 具体精简版主题的容量。借助精简版预留,您可以管理和 监控的资源更少此外,您不必选择吞吐量容量 各个精简版主题。

如需使用精简版预留,您需要附加一个精简版主题,该主题位于 与特定的精简版预留相关联您可以将单个精简版 可用区级和区域级精简版主题的预留资源同一个 Pod 中的所有分区 附加到精简版预留的精简版主题会动态使用 从精简版预留中预配的吞吐量容量减少如果您 为精简版主题指定精简版预留,还可以添加费率 限制精简版主题每个分区的吞吐量容量。

容量单位概览

精简版预留的吞吐量容量以容量单位为单位预配。

一个容量单位对应于以下吞吐量:

精简版主题类型 发布吞吐量 (MiBps) 订阅吞吐量(以 MiBps 为单位)
可用区级 1 2
区域 0.25 0.5

预留命名准则

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 调用时,此格式非常重要。

精简版预留使用准则

对于区域级精简版,必须使用精简版预留预配吞吐量 主题;对于可用区级精简版主题,是可选属性。精简版预留 资源。

计划配置 Lite 时,请注意以下事项 预留:

  • 精简版预留所需的容量单元数量必须等于 所有主题和在任意给定一分钟内预期的吞吐量峰值 该精简版预留中的订阅。

  • 一个精简版预留中所有精简版主题的吞吐量总和 达到其容量时,发布和传送会受到限制。 Pub/Sub Lite 服务器停止向客户端发送消息, 消息在发布者客户端中进行缓冲。您可以为以下事件设置提醒: reservation/throughput_capacity/utilization告知您 因此预留可能会受到限制 预留大小

  • 您可以随时更新预留的吞吐量。 更改将在一分钟内生效。不过,如果您将 预留的吞吐量,您仍将为 计算Pub/Sub Lite 本质上是为容量付费的 可以实现即时纵向扩容,并可进行纵向缩容。

  • 附加到精简版预留的所有精简版主题都使用 最大吞吐量容量因此,精简版主题可能会突然使用 吞吐量容量较大,会耗尽其他 Lite 主题, 禁止它们发布或接收消息。如果您需要完全隔离 您可以将它们附加到独立的预留中。

分区对精简版预留的影响

精简版预留中所有精简版主题的分区总数必须 不得超过预留的容量单元数。例如,您 无法将包含 10 个容量单元的精简版预留附加到一个精简版主题或一组 分区总数超过 10 的精简版主题。

计算精简版预留的容量单位

精简版预留的大小由容量单元数定义。通过 以下示例说明了如何估算 各个精简版主题。

  1. 确定发布吞吐量峰值。

    预估挂接到指定资源的所有精简版主题的吞吐量峰值 精简版预留。吞吐量的粗略估计是 这样就足够了,因为您可以随时更新预留的大小。

  2. 确定订阅吞吐量峰值。

    订阅吞吐量峰值的计算方法类似于发布峰值 吞吐量。不过请注意,订阅者并不一定需要 以发布商的峰值速率接收消息。如果处理延迟 Pub/Sub Lite 可让您缓冲消息 稳定地处理它们。同时,您可能希望获得更多 与发布容量相比, 订阅者的停机时间

  3. 确定所需的容量单元的总数。

    上一部分中的表指定了 MiBps 的数量 一个容量单元为不同操作所能容纳的容量。以下 是用于计算样本所需容量单位的公式 精简版预留:

    • 可用区级精简版主题的发布吞吐量峰值 = Pz MiBps
    • 区域级精简版主题的峰值发布吞吐量 = Pr MiBps
    • 可用区级精简版主题的订阅吞吐量峰值 = Sz MiBps
    • 区域级精简版主题的峰值订阅吞吐量 = Sr MiBps

      所需的容量单位数 = (Pz / 1 MiBps) + (Pr/0.25 MiBps) + (Sz/2 MiBps) + (Sr/0.5 MiBps)

      如果数值不是整数,则必须向上舍入。

在没有精简版预留的情况下配置吞吐量容量

  • 主题发布吞吐量容量:您可以指定 4 到 16 MiBps 吞吐量容量,并且值必须为整数。

  • 主题订阅吞吐量容量:您可以指定 4-32 MiBps 吞吐量容量,并且值必须为整数。

对于订阅吞吐量,我们建议您预配吞吐量 等于预期发布吞吐量的乘积 有关您主题的订阅数量。

为单个主题预配的发布者和订阅者容量不可互换。处于这个原因,我们建议始终使用预留。

直接为 Cloud Storage 预配容量时,结算存在差异 而不是使用预留请参阅 Pub/Sub 精简版价格页面 了解详情。

创建精简版预留

精简版预留必须与任何精简版主题位于同一项目和区域中 其他对象。如需查看可用可用区和区域的列表,请参阅 Pub/Sub 精简版位置

您可以使用 Google Cloud 控制台、 Google Cloud CLI 或 Pub/Sub Lite API

控制台

  1. 转到精简版预留页面。

    前往精简版预留

  2. 点击创建精简版预留

  3. 请选择区域。

  4. 输入精简版预留 ID

  5. 预配吞吐量容量单位的数量。

  6. 点击创建

gcloud

要创建精简版预留,请使用 gcloud pubsub lite-reservations create 命令:

gcloud pubsub lite-reservations create myRes \
  --location=us-central1 \
  --throughput-capacity=INTEGER_NUMBER_OF_UNITS
gcloud pubsub lite-topics create myTopic \
  --throughput-reservation=myRez \
  --zone=ZONE \
  --location=us-central1a \
  --partitions \
  --storage

Go

在运行此示例之前,请按照 Pub/Sub Lite 客户端库

import (
	"context"
	"fmt"
	"io"

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

func createReservation(w io.Writer, projectID, region, reservationID string, throughputCapacity int) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// reservationID := "my-reservation"
	// throughputCapacity := 4
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	reservationPath := fmt.Sprintf("projects/%s/locations/%s/reservations/%s", projectID, region, reservationID)
	res, err := client.CreateReservation(ctx, pubsublite.ReservationConfig{
		Name:               reservationPath,
		ThroughputCapacity: throughputCapacity,
	})
	if err != nil {
		return fmt.Errorf("client.CreateReservation got err: %w", err)
	}
	fmt.Fprintf(w, "Created reservation: %s\n", res.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.ProjectNumber;
import com.google.cloud.pubsublite.ReservationName;
import com.google.cloud.pubsublite.ReservationPath;
import com.google.cloud.pubsublite.proto.Reservation;
import java.util.concurrent.ExecutionException;

public class CreateReservationExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    long projectNumber = Long.parseLong("123456789");
    String cloudRegion = "your-cloud-region";
    String reservationId = "your-reservation-id";
    // Each unit of throughput capacity supports up to 1 MiB/s of published messages or
    // 2 MiB/s of subscribed messages.
    int throughputCapacity = 4;

    createReservationExample(projectNumber, cloudRegion, reservationId, throughputCapacity);
  }

  public static void createReservationExample(
      long projectNumber, String cloudRegion, String reservationId, int throughputCapacity)
      throws Exception {

    ReservationPath reservationPath =
        ReservationPath.newBuilder()
            .setProject(ProjectNumber.of(projectNumber))
            .setLocation(CloudRegion.of(cloudRegion))
            .setName(ReservationName.of(reservationId))
            .build();

    Reservation reservation =
        Reservation.newBuilder()
            .setName(reservationPath.toString())
            .setThroughputCapacity(throughputCapacity)
            .build();

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

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Reservation response = adminClient.createReservation(reservation).get();
      System.out.println(response.getAllFields() + " created successfully.");
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (AlreadyExistsException alreadyExists) {
        System.out.println("This reservation 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, Reservation
from google.cloud.pubsublite.types import CloudRegion, ReservationPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# reservation_id = "your-reservation-id"
# Each unit of throughput capacity supports up to 1 MiB/s of published messages
# or 2 MiB/s of subscribed messages. Must be a positive integer.
# throughput_capacity = 4

cloud_region = CloudRegion(cloud_region)
reservation_path = ReservationPath(project_number, cloud_region, reservation_id)

reservation = Reservation(
    name=str(reservation_path),
    throughput_capacity=throughput_capacity,
)

client = AdminClient(cloud_region)
try:
    response = client.create_reservation(reservation)
    print(f"{response.name} created successfully.")
except AlreadyExists:
    print(f"{reservation_path} already exists.")

更新精简版预留

您可以更新为精简版预留配置的容量单元数。

您可以使用 Google Cloud 控制台、 Google Cloud CLI 或 Pub/Sub Lite API

控制台

  1. 转到精简版预留页面。

    前往精简版预留

  2. 点击精简版预留 ID。

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

gcloud

要更新精简版预留,请使用 gcloud pubsub lite-reservations update 命令:

gcloud pubsub lite-reservations update RESERVATION_ID \
  --location=REGION \
  --throughput-capacity=THROUGHPUT_CAPACITY

替换以下内容:

  • RESERVATION_ID:精简版预留的 ID
  • REGION:预留的区域
  • THROUGHPUT_CAPACITY:预留吞吐量容量。

Go

在运行此示例之前,请按照 Pub/Sub Lite 客户端库

import (
	"context"
	"fmt"
	"io"

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

func updateReservation(w io.Writer, projectID, region, reservationID string, throughputCapacity int) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// reservationID := "my-reservation-id"
	// throughputCapacity := 8
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	reservationPath := fmt.Sprintf("projects/%s/locations/%s/reservations/%s", projectID, region, reservationID)
	config := pubsublite.ReservationConfigToUpdate{
		Name:               reservationPath,
		ThroughputCapacity: throughputCapacity,
	}
	updatedCfg, err := client.UpdateReservation(ctx, config)
	if err != nil {
		return fmt.Errorf("client.UpdateReservation got err: %w", err)
	}
	fmt.Fprintf(w, "Updated reservation: %#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.ProjectNumber;
import com.google.cloud.pubsublite.ReservationName;
import com.google.cloud.pubsublite.ReservationPath;
import com.google.cloud.pubsublite.proto.Reservation;
import java.util.concurrent.ExecutionException;

public class UpdateReservationExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    long projectNumber = Long.parseLong("123456789");
    String cloudRegion = "your-cloud-region";
    String reservationId = "your-reservation-id";
    // Each unit of throughput capacity supports up to 1 MiB/s of published messages or
    // 2 MiB/s of subscribed messages.
    int throughputCapacity = 8;

    updateReservationExample(projectNumber, cloudRegion, reservationId, throughputCapacity);
  }

  public static void updateReservationExample(
      long projectNumber, String cloudRegion, String reservationId, int throughputCapacity)
      throws Exception {

    ReservationPath reservationPath =
        ReservationPath.newBuilder()
            .setProject(ProjectNumber.of(projectNumber))
            .setLocation(CloudRegion.of(cloudRegion))
            .setName(ReservationName.of(reservationId))
            .build();

    com.google.protobuf.FieldMask fieldMask =
        com.google.protobuf.FieldMask.newBuilder().addPaths("throughput_capacity").build();

    Reservation reservation =
        Reservation.newBuilder()
            .setName(reservationPath.toString())
            .setThroughputCapacity(throughputCapacity)
            .build();

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

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Reservation reservationBeforeUpdate = adminClient.getReservation(reservationPath).get();
      System.out.println("Before update: " + reservationBeforeUpdate.getAllFields());

      Reservation reservationAfterUpdate =
          adminClient.updateReservation(reservation, fieldMask).get();
      System.out.println("After update: " + reservationAfterUpdate.getAllFields());
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This reservation 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, Reservation
from google.cloud.pubsublite.types import CloudRegion, ReservationPath
from google.protobuf.field_mask_pb2 import FieldMask

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# reservation_id = "your-reservation-id"
# Each unit of throughput capacity supports up to 1 MiB/s of published messages
# or 2 MiB/s of subscribed messages. Must be a positive integer.
# throughput_capacity = 8

cloud_region = CloudRegion(cloud_region)
reservation_path = ReservationPath(project_number, cloud_region, reservation_id)

# Defines which fields to update in the reservation.
field_mask = FieldMask(paths=["throughput_capacity"])

reservation = Reservation(
    name=str(reservation_path), throughput_capacity=throughput_capacity
)

client = AdminClient(cloud_region)
try:
    response = client.get_reservation(reservation_path)
    print(f"Before update: {response}")

    response = client.update_reservation(reservation, field_mask)
    print(f"After update: {response}")
except NotFound:
    print(f"{reservation_path} is not found.")

获取精简版预留详情

您可以使用 Google Cloud 控制台、 Google Cloud CLI 或 Pub/Sub Lite API

控制台

  1. 转到精简版预留页面。

    前往精简版预留

  2. 点击精简版预留 ID。

gcloud

要获取精简版预留的详细信息,请使用 gcloud pubsub lite-reservations describe 命令:

gcloud pubsub lite-reservations describe RESERVATION_ID \
  --location=REGION

替换以下内容:

  • RESERVATION_ID:精简版预留的 ID
  • REGION:预留的区域

Go

在运行此示例之前,请按照 Pub/Sub Lite 客户端库

import (
	"context"
	"fmt"
	"io"

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

func getReservation(w io.Writer, projectID, region, reservationID string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// reservationID := "my-reservation"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	reservationPath := fmt.Sprintf("projects/%s/locations/%s/reservations/%s", projectID, region, reservationID)
	res, err := client.Reservation(ctx, reservationPath)
	if err != nil {
		return fmt.Errorf("client.Reservation got err: %w", err)
	}
	fmt.Fprintf(w, "Got reservation: %#v\n", res)
	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.ProjectNumber;
import com.google.cloud.pubsublite.ReservationName;
import com.google.cloud.pubsublite.ReservationPath;
import com.google.cloud.pubsublite.proto.Reservation;
import java.util.concurrent.ExecutionException;

public class GetReservationExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    long projectNumber = Long.parseLong("123456789");
    String cloudRegion = "your-cloud-region";
    String reservationId = "your-reservation-id";

    getReservationExample(projectNumber, cloudRegion, reservationId);
  }

  public static void getReservationExample(
      long projectNumber, String cloudRegion, String reservationId) throws Exception {
    ReservationPath reservationPath =
        ReservationPath.newBuilder()
            .setProject(ProjectNumber.of(projectNumber))
            .setLocation(CloudRegion.of(cloudRegion))
            .setName(ReservationName.of(reservationId))
            .build();

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

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Reservation response = adminClient.getReservation(reservationPath).get();
      long throughputCapacity = response.getThroughputCapacity();
      System.out.println(
          response.getAllFields()
              + "\nhas "
              + throughputCapacity
              + " units of throughput capacity.");
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This reservation 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, ReservationPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# reservation_id = "your-reservation-id"

cloud_region = CloudRegion(cloud_region)
reservation_path = ReservationPath(project_number, cloud_region, reservation_id)

client = AdminClient(cloud_region)
try:
    response = client.get_reservation(reservation_path)
    print(
        f"{response.name} has {response.throughput_capacity} units of throughput capacity."
    )
except NotFound:
    print(f"{reservation_path} is not found.")

列出精简版预留

控制台

gcloud

要查看项目中的精简版预留列表,请使用 gcloud pubsub lite-reservations list 命令:

gcloud pubsub lite-reservations list \
  --location=REGION

替换以下内容:

  • REGION:预留的区域

Go

在运行此示例之前,请按照 Pub/Sub Lite 客户端库

import (
	"context"
	"fmt"
	"io"

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

func listReservations(w io.Writer, projectID, region string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)
	resIter := client.Reservations(ctx, parent)
	for {
		res, err := resIter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("resIter.Next() got err: %w", err)
		}
		fmt.Fprintf(w, "Got reservation config: %v", res)
	}
	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.LocationPath;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.proto.Reservation;
import java.util.List;

public class ListReservationsExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    long projectNumber = Long.parseLong("123456789");
    String cloudRegion = "your-cloud-region";

    listReservationsExample(projectNumber, cloudRegion);
  }

  public static void listReservationsExample(long projectNumber, String cloudRegion)
      throws Exception {

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

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

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      List<Reservation> reservations = adminClient.listReservations(locationPath).get();
      for (Reservation reservation : reservations) {
        System.out.println(reservation.getAllFields());
      }
      System.out.println(reservations.size() + " reservation(s) listed in " + locationPath + ".");
    }
  }
}

Python

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

from google.cloud.pubsublite import AdminClient
from google.cloud.pubsublite.types import LocationPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"

location_path = LocationPath(project_number, cloud_region)

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

for reservation in response:
    print(reservation)

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

删除精简版预留

您可以通过 Google Cloud 控制台、 Google Cloud CLI 或 Pub/Sub Lite API为了删除预留 不得包含任何主题。您可以将现有主题关联到其他预留,然后再删除预留。

控制台

  1. 转到精简版预留页面。

    前往精简版预留

  2. 点击精简版预留 ID。

  3. 在精简版预留详情页面中,点击删除

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

gcloud

要删除精简版预留,请使用 gcloud pubsub lite-reservations delete 命令:

gcloud pubsub lite-reservations delete RESERVATION_ID \
  --location=REGION

替换以下内容:

  • RESERVATION_ID:精简版预留的 ID
  • REGION:预留的区域

Go

在运行此示例之前,请按照 Pub/Sub Lite 客户端库

import (
	"context"
	"fmt"
	"io"

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

func deleteReservation(w io.Writer, projectID, region, reservationID string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// reservationID := "my-reservation"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	reservationPath := fmt.Sprintf("projects/%s/locations/%s/reservations/%s", projectID, region, reservationID)
	err = client.DeleteReservation(ctx, reservationPath)
	if err != nil {
		return fmt.Errorf("client.DeleteReservation got err: %w", err)
	}
	fmt.Fprint(w, "Deleted reservation")
	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.ProjectNumber;
import com.google.cloud.pubsublite.ReservationName;
import com.google.cloud.pubsublite.ReservationPath;
import java.util.concurrent.ExecutionException;

public class DeleteReservationExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    long projectNumber = Long.parseLong("123456789");
    String cloudRegion = "your-cloud-region";
    String reservationId = "your-reservation-id";

    deleteReservationExample(projectNumber, cloudRegion, reservationId);
  }

  public static void deleteReservationExample(
      long projectNumber, String cloudRegion, String reservationId) throws Exception {

    ReservationPath reservationPath =
        ReservationPath.newBuilder()
            .setProject(ProjectNumber.of(projectNumber))
            .setLocation(CloudRegion.of(cloudRegion))
            .setName(ReservationName.of(reservationId))
            .build();

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

    // If a reservation has topics attached, you must delete the topics before deleting
    // the reservation.
    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      adminClient.deleteReservation(reservationPath).get();
      System.out.println(reservationPath + " deleted successfully.");
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This reservation 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, ReservationPath

# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# reservation_id = "your-reservation-id"

cloud_region = CloudRegion(cloud_region)
reservation_path = ReservationPath(project_number, cloud_region, reservation_id)

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

后续步骤