Lite サブスクリプションを作成して管理する

サブスクライバーは Lite サブスクリプションを使用して Lite トピックからメッセージを読みます。Lite サブスクリプションを作成する際に、Lite トピックに追加します。単一の Lite トピックに多数の Lite サブスクリプションを追加できます。

サブスクリプションには次の 2 種類があります。

  • 標準サブスクリプションLite トピックからメッセージを読み取る必要があるクライアントがいる場合は、標準サブスクリプションを作成します。
  • エクスポート サブスクリプション。Lite メッセージを Pub/Sub にエクスポートする必要がある場合は、エクスポート サブスクリプションを作成します。詳細については、Pub/Sub Lite メッセージを Pub/Sub にエクスポートするをご覧ください。

Lite サブスクリプションのプロパティ

ゾーン Lite トピックのサブスクリプションには、次の点を除いて、リージョン Lite トピックのサブスクリプションと同じプロパティがあります。

  • リソース名で使用されるロケーション タイプ、ゾーンまたはリージョン。リージョンのロケーションの例は us-central1 です。たとえば、ゾーンのロケーションは us-central1-a です。

  • 信頼性。リージョン トピックとゾーン トピックの信頼性の違いについて詳しくは、Lite トピックのデータ レプリケーションをご覧ください。

メッセージの配信要件

ストレージへのメッセージの書き込みで一時的な障害が発生すると、パブリッシャーはメッセージの送信を再試行します。この再試行は、エンドユーザーにとって透過的です。Lite サブスクリプションには、メッセージの再試行に対するサブスクリプションの反応を変更する配信要件プロパティがあります。このプロパティは、次の 2 つのオプションのいずれかに設定できます。

  • すぐにメッセージを配信する。このオプションを有効にすると、サブスクライバー クライアントはサーバーに到着した後にすべてのメッセージを受信します。このプロセスは、ディスクに書き込まれるメッセージのステータスに依存しません。オフセットは再利用されませんが、ストレージに書き込まれないオフセット付きメッセージは、シーク オペレーション後に再読み取りできない可能性があります。

  • 保存後にメッセージを配信する。このオプションを有効にすると、サブスクライバーはディスクに書き込まれるまでメッセージを受信しません。これらのメッセージは、シーク オペレーション後に再度読み取り可能になります。このオプションを有効にすると、パブリッシャーからサブスクライバーへのメッセージ受信に対し、エンドツーエンドのレイテンシが増加します。

サブスクリプションへの名前付けのガイドライン

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]、ダッシュ -、アンダースコア _、ピリオド .、チルダ ~、プラス記号 +、パーセント記号 %

    URL エンコードのないリソース名で、上記のリストの特殊文字を使用できます。ただし、URL で使用されている場合、その他すべての特殊文字が適切にエンコードまたはデコードされることを確認する必要があります。たとえば、mi-tópico は無効な ID です。mi-t%C3%B3pico は有効です。この形式は、REST 呼び出しを行うときに重要です。

Lite サブスクリプションの作成

Lite サブスクリプションは、Lite サブスクリプションが関連付けられた Lite トピックと同じプロジェクトとロケーションに存在している必要があります。

Lite トピックを作成するには、Lite トピックを作成して管理するをご覧ください。

使用可能なロケーションのリストについては、Pub/Sub Lite のロケーションをご覧ください。

Lite サブスクリプションは、Google Cloud コンソール、Google Cloud CLI、または Pub/Sub Lite API を使用して作成できます。

エクスポート サブスクリプションの作成については、Pub/Sub Lite メッセージを Pub/Sub にエクスポートするをご覧ください。

Console

  1. [Lite サブスクリプション] ページに移動します。

    [Lite サブスクリプション] に移動

  2. [Lite サブスクリプションを作成] をクリックします。

  3. Lite サブスクリプション ID を入力します。

  4. メッセージを受信する Lite トピックを選択します。

  5. [すぐにメッセージを配信] または [保存後にメッセージを配信] を選択します。

  6. [開始オフセット] のタイプを選択します。

  7. [配信タイプ] を選択します。

  8. [Create(作成)] をクリックします。

gcloud

Lite サブスクリプションを作成するには、gcloud pubsub lite-subscriptions create コマンドを使用します。

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

以下を置き換えます。

  • SUBSCRIPTION_ID: Lite サブスクリプションの ID

  • LOCATION: Pub/Sub Lite がサポートするロケーションの名前

  • TOPIC_ID: Lite サブスクリプションに関連付ける Lite トピックの ID。

  • DELIVERY_REQUIREMENT: deliver-after-stored または deliver-immediately

リクエストが成功すると、コマンドラインに確認メッセージが表示されます。

Created [SUBSCRIPTION_ID].

プロトコル

Lite サブスクリプションを作成するには、次のような POST リクエストを送信します。

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

次のように置き換えます。

リクエスト本文に次のフィールドを指定します。

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

DELIVERY_REQUIREMENT は、deliver-after-stored または deliver-immediately に置き換えます。

リクエストが成功した場合のレスポンスは、JSON 形式の Lite サブスクリプションになります。

{
  "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 Lite クライアント ライブラリの 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.")

Lite トピックに Lite サブスクリプションを作成すると、Lite サブスクリプションからメッセージを受信できるようになります。

Lite サブスクリプションを更新する

Lite サブスクリプションは、Google Cloud コンソール、Google Cloud CLI、または Pub/Sub Lite API を使用して更新できます。

Console

  1. [Lite サブスクリプション] ページに移動します。

    [Lite サブスクリプション] に移動

  2. [Lite サブスクリプション ID] をクリックします。

  3. [Lite サブスクリプションの詳細] ページで [編集] をクリックします。

gcloud

Lite サブスクリプションを更新するには、gcloud pubsub lite-subscriptions update コマンドを使用します。

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

以下を置き換えます。

  • SUBSCRIPTION_ID: Lite サブスクリプションの ID

  • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

  • DELIVERY_REQUIREMENT: deliver-after-stored または deliver-immediately

リクエストが成功すると、コマンドラインに Lite サブスクリプションが表示されます。

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

プロトコル

Lite サブスクリプションを更新するには、次のような 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: Lite サブスクリプションを保存するリージョン

  • PROJECT_NUMBER: Lite サブスクリプションを持つプロジェクトのプロジェクト番号

  • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

  • SUBSCRIPTION_ID: Lite サブスクリプションの ID

リクエスト本文に次のフィールドを指定します。

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

DELIVERY_REQUIREMENT は、deliver-after-stored または deliver-immediately に置き換えます。

リクエストが成功した場合のレスポンスは、JSON 形式の Lite サブスクリプションになります。

{
  "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 Lite クライアント ライブラリの 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.")

Lite サブスクリプションの詳細を表示する

Lite トピックの詳細は、Google Cloud コンソール、Google Cloud CLI、または Pub/Sub Lite API を使用して取得できます。

Console

  1. [Lite サブスクリプション] ページに移動します。

    [Lite サブスクリプション] に移動

  2. [Lite サブスクリプション ID] をクリックします。

  3. [Lite サブスクリプションの詳細] ページで [詳細] タブをクリックします。

gcloud

Lite サブスクリプションの詳細を取得するには、gcloud pubsub lite-subscriptions describe コマンドを使用します。

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

以下を置き換えます。

  • SUBSCRIPTION_ID: Lite サブスクリプションの ID

  • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

リクエストが成功すると、コマンドラインに Lite トピックが表示されます。

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

プロトコル

Lite サブスクリプションの詳細を取得するには、次のような 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: Lite サブスクリプションを保存するリージョン

  • PROJECT_NUMBER: Lite サブスクリプションを持つプロジェクトのプロジェクト番号

  • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

  • SUBSCRIPTION_ID: Lite サブスクリプションの ID

リクエストが成功すると、レスポンスは JSON 形式の Lite トピックになります。

{
  "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 Lite クライアント ライブラリの 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.")

Lite サブスクリプションを一覧表示する

プロジェクト内の Lite サブスクリプションまたは、Lite トピックの Lite サブスクリプションを一覧表示できます。

プロジェクト内の Lite サブスクリプションを一覧表示する

Google Cloud コンソール、Google Cloud CLI、または Pub/Sub Lite API を使用して、プロジェクト内の Lite トピックを一覧表示できます。

Console

gcloud

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

LOCATION は、Lite サブスクリプションがあるロケーションの名前に置き換えます。

リクエストが成功すると、コマンドラインに Lite サブスクリプションが表示されます。

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

プロトコル

  • プロジェクト内の Lite サブスクリプションを一覧表示するには、次のように GET リクエストを送信します。
GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/subscriptions
Authorization: Bearer $(gcloud auth print-access-token)

次のように置き換えます。

  • REGION: Lite サブスクリプションを保存するリージョン

  • PROJECT_NUMBER: Lite サブスクリプションを持つプロジェクトのプロジェクト番号

リクエストが成功すると、レスポンスは JSON 形式の Lite トピックになります。

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

Go

このサンプルを実行する前に、Pub/Sub Lite クライアント ライブラリの 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.")

Lite トピックの Lite サブスクリプションを一覧表示する

Google Cloud コンソール、Google Cloud CLI、または Pub/Sub Lite API を使用して、Lite トピックに Lite サブスクリプションを一覧表示できます。

Console

  1. [Lite トピック] ページに移動します。

    [Lite トピック] に移動

  2. [Lite トピック ID] を選択します。

  3. [Lite トピック] 詳細ページの [Lite サブスクリプション] セクションに、Lite トピックの Lite サブスクリプションのリストが含まれます。

gcloud

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

以下を置き換えます。

  • TOPIC_ID: Lite サブスクリプションが関連付けられた Lite トピックの ID

  • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

リクエストが成功すると、コマンドラインに Lite サブスクリプションが表示されます。

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

プロトコル

  • Lite トピックの Lite サブスクリプションを一覧表示するには、次のような 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: Lite サブスクリプションを保存するリージョン

  • PROJECT_NUMBER: Lite サブスクリプションを持つプロジェクトのプロジェクト番号

  • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

  • TOPIC_ID: Lite サブスクリプションが関連付けられた Lite トピックの ID

リクエストが成功した場合、レスポンスは JSON 形式の Lite サブスクリプションのリストになります。

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

Go

このサンプルを実行する前に、Pub/Sub Lite クライアント ライブラリの 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.")

Lite サブスクリプションを削除する

Lite サブスクリプションは、Google Cloud コンソール、Google Cloud CLI、または Pub/Sub Lite API を使用して削除できます。

Console

  1. [Lite サブスクリプション] ページに移動します。

    [Lite サブスクリプション] に移動

  2. [Lite サブスクリプション ID] をクリックします。

  3. [Lite サブスクリプションの詳細] ページで [削除] をクリックします。

  4. 表示されたダイアログで [削除] をクリックして、削除する Lite サブスクリプションの削除を確定します。

gcloud

Lite サブスクリプションを削除するには、gcloud pubsub lite-subscriptions delete コマンドを使用します。

  1. delete コマンドを実行します。

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

    以下を置き換えます。

    • SUBSCRIPTION_ID: Lite サブスクリプションの ID

    • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

  2. 確定するには「Y」と入力します。

リクエストが成功すると、コマンドラインに確認メッセージが表示されます。

Deleted subscription [SUBSCRIPTION_ID].

プロトコル

  • Lite トピックを削除するには、次のような 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: Lite サブスクリプションを保存するリージョン

  • PROJECT_NUMBER: Lite サブスクリプションを持つプロジェクトのプロジェクト番号

  • LOCATION: Lite サブスクリプションが含まれるロケーションの名前

  • SUBSCRIPTION_ID: Lite サブスクリプションの ID

リクエストが成功した場合のレスポンスは空の JSON オブジェクトです。

Go

このサンプルを実行する前に、Pub/Sub Lite クライアント ライブラリの 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.")

次のステップ