라이트 예약 만들기 및 관리

이 문서에서는 Pub/Sub Lite 예약을 사용하고 관리하는 방법을 설명합니다. 이 문서에서는 또한 용량 단위의 개념과 애플리케이션의 처리량 수용을 위해 필요한 수량 확인 방법을 설명합니다.

라이트 예약 개요

라이트 예약은 한 리전에서 하나 또는 여러 라이트 주제 간에 처리량 용량을 프로비저닝하고 동적으로 공유합니다. 이러한 주제는 리전 또는 영역별 라이트 주제일 수 있습니다. 라이트 예약을 사용하는 것이 개별 라이트 주제의 처리량 용량을 설정하는 것보다 더 좋은 옵션입니다. 라이트 예약을 사용하면 관리 및 모니터링하는 리소스 수가 줄어듭니다. 또한 개별 라이트 주제의 처리 용량을 선택할 필요가 없습니다.

라이트 예약을 사용하려면 동일한 리전에 있는 라이트 주제를 특정 라이트 예약에 연결합니다. 단일 라이트 예약을 영역별 및 리전별 라이트 주제에 모두 연결할 수 있습니다. 라이트 예약에 연결된 라이트 주제의 모든 파티션은 라이트 예약에 프로비저닝된 처리 용량에서 동적으로 소비됩니다. 라이트 주제에 라이트 예약을 지정할 경우 비율 제한을 포함하여 라이트 주제의 각 파티션의 처리 용량을 제한할 수도 있습니다.

용량 단위 개요

라이트 예약의 처리량 용량은 용량 단위로 프로비저닝됩니다.

하나의 용량 단위는 다음과 같은 처리량에 해당됩니다.

라이트 주제 유형 게시 처리량(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: topics, subscriptions, reservations 중 하나여야 합니다.

  • ID: 다음 가이드라인을 준수하세요.

    • goog 문자열로 시작하지 않도록 합니다.
    • 문자로 시작합니다.
    • 3~255자여야 합니다.
    • 다음 문자(글자 [A-Za-z], 숫자 [0-9], 대시 -, 밑줄 _, 마침표 ., 물결표 ~, 더하기 기호 +, 퍼센트 기호 %)만 포함해야 합니다.

    URL로 인코딩하지 않고 리소스 이름에 이전 목록의 특수문자를 사용할 수 있습니다. 하지만 다른 특수문자를 URL에 사용하는 경우 올바르게 암호화되거나 디코딩되었는지 확인해야 합니다. 예를 들어 mi-tópico는 잘못된 ID입니다. 그러나 mi-t%C3%B3pico는 유효합니다. 이 형식은 REST를 호출할 때 중요합니다.

라이트 예약 사용 가이드라인

라이트 예약으로 처리량을 프로비저닝하는 것은 리전 라이트 주제의 경우 필수이며 영역 라이트 주제의 경우 선택사항입니다. 라이트 예약은 리전별 리소스입니다.

라이트 예약을 구성할 때는 다음 사항에 유의하세요.

  • 라이트 예약에 필요한 용량 단위 수는 해당 라이트 예약의 모든 주제 및 구독에서 1분 동안 예상되는 최대 처리량과 동일해야 합니다.

  • 라이트 예약에서 모든 라이트 주제의 결합 처리량이 용량에 도달하면 게시 및 전송이 조정됩니다. Pub/Sub Lite 서버가 클라이언트로의 메시지 전송을 중지하고 메시지가 게시자 클라이언트에 버퍼링됩니다. 예약 크기를 늘릴 수 있도록 예약이 제한될 위험이 있는 경우 reservation/throughput_capacity/utilization에 대한 알림을 설정할 수 있습니다.

  • 원하는 경우 예약 처리량을 업데이트할 수 있습니다. 변경사항은 1분 이내에 적용됩니다. 그러나 예약 처리량을 줄이면 24시간 동안 더 높은 금액이 계속 청구됩니다. Pub/Sub 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~16MiBps를 처리량 용량으로 지정할 수 있으며 이 값은 정수여야 합니다.

  • 주제 구독 처리량 용량: 4~32MiBps를 처리량 용량으로 지정할 수 있으며 이 값은 정수여야 합니다.

구독 처리량의 경우 주제의 예상 게시 처리량 및 구독 수의 제품과 동일하게 처리량 용량을 프로비저닝하는 것이 좋습니다.

개별 주제에 프로비저닝된 게시자 및 구독자 용량은 서로 바꿔서 사용할 수 없습니다. 따라서 항상 예약을 사용하는 것이 좋습니다.

참고: 예약을 사용하는 대신 주제에 용량을 직접 프로비저닝할 때 청구 비용 간에 차이가 있습니다. 자세한 내용은 Pub/Sub Lite 가격 책정 페이지를 참조하세요.

라이트 예약 만들기

라이트 예약은 연결된 라이트 주제와 동일한 프로젝트 및 리전에 있어야 합니다. 사용 가능한 영역 및 리전 목록은 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 클라이언트 라이브러리의 Go 설정 안내를 따르세요.

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
}

자바

이 샘플을 실행하기 전에 Pub/Sub Lite 클라이언트 라이브러리의 자바 설정 안내를 따르세요.

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 클라이언트 라이브러리의 Go 설정 안내를 따르세요.

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
}

자바

이 샘플을 실행하기 전에 Pub/Sub Lite 클라이언트 라이브러리의 자바 설정 안내를 따르세요.

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 클라이언트 라이브러리의 Go 설정 안내를 따르세요.

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
}

자바

이 샘플을 실행하기 전에 Pub/Sub Lite 클라이언트 라이브러리의 자바 설정 안내를 따르세요.

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 클라이언트 라이브러리의 Go 설정 안내를 따르세요.

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
}

자바

이 샘플을 실행하기 전에 Pub/Sub Lite 클라이언트 라이브러리의 자바 설정 안내를 따르세요.

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 Console, 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 클라이언트 라이브러리의 Go 설정 안내를 따르세요.

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
}

자바

이 샘플을 실행하기 전에 Pub/Sub Lite 클라이언트 라이브러리의 자바 설정 안내를 따르세요.

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.")

다음 단계