Lite-Abos erstellen und verwalten

Abonnenten verwenden ein Lite-Abo, um Nachrichten aus einem Lite-Thema zu lesen. Wenn Sie ein Lite-Abo erstellen, hängen Sie es an ein Lite-Thema an. Sie können mehrere Lite-Abos mit einem einzelnen Lite-Thema verknüpfen.

Es gibt zwei Arten von Abos:

  • Standardabo. Erstellen Sie ein Standardabo, wenn Sie einen Client haben, der Nachrichten aus dem Lite-Thema lesen muss.
  • Abo exportieren Erstellen Sie ein Exportabo, wenn Sie Lite-Nachrichten nach Pub/Sub exportieren müssen. Weitere Informationen finden Sie unter Pub/Sub Lite-Nachrichten nach Pub/Sub exportieren.

Eigenschaften eines Lite-Abos

Ein Abo für ein zonales Lite-Thema hat bis auf Folgendes dieselben Attribute wie ein Abo für ein regionales Lite-Thema:

  • Standorttyp, Zone oder Region, der im Ressourcennamen verwendet wird. Ein Beispiel für einen regionalen Standort ist us-central1. Ein Beispiel für einen Zonenstandort ist us-central1-a.

  • Zuverlässigkeit. Weitere Informationen zu Zuverlässigkeitsunterschieden zwischen regionalen und zonalen Themen finden Sie unter Datenreplikation in einem Lite-Thema.

Zustellanforderung für Nachrichten

Ein vorübergehender Fehler beim Schreiben einer Nachricht in den Speicher führt dazu, dass der Verlag oder Webpublisher die Nachricht noch einmal sendet. Diese Wiederholungsversuche sind für den Endnutzer transparent. Lite-Abos haben ein Attribut für die Zustellungsanforderung, das die Reaktion von Abos auf diese wiederholten Nachrichten ändert. Sie können dieses Attribut auf eine der folgenden zwei Optionen festlegen:

  • Nachrichten sofort senden: Wenn diese Option aktiviert ist, erhalten die Abonnentenclients alle Nachrichten, nachdem sie auf dem Server eingegangen sind. Dieser Vorgang hängt nicht vom Status der Nachrichten ab, die auf das Laufwerk geschrieben werden. Offsets werden nicht wiederverwendet, aber Nachrichten mit Offsets, die nicht in den Speicher geschrieben werden, sind nach einem seek-Vorgang möglicherweise nicht wieder lesbar.

  • Nachrichten nach dem Speichern senden. Wenn diese Option aktiviert ist, erhält der Abonnent Nachrichten erst, wenn sie auf das Laufwerk geschrieben werden. Die Nachrichten sind nach einem Suchvorgang garantiert wieder lesbar. Wenn Sie diese Option aktivieren, wird die End-to-End-Latenz für den Empfang von Nachrichten vom Publisher an den Abonnenten erhöht.

Richtlinien für die Benennung von Abos

Ein Pub/Sub Lite-Ressourcenname identifiziert eine Pub/Sub Lite-Ressource eindeutig, z. B. ein Thema, ein Abo oder eine Reservierung. Der Ressourcenname muss das folgende Format haben:

projects/project-identifier/collection/ID

  • project-identifier: Muss die Projekt-ID oder Projektnummer sein, die in der Google Cloud Console verfügbar ist. my-cool-project ist beispielsweise eine Projekt-ID. 123456789123 ist eine Projektnummer.

  • collection: muss topics, subscriptions oder reservations sein.

  • ID: Muss den folgenden Richtlinien entsprechen:

    • Sie dürfen nicht mit dem String „goog“ beginnen.
    • Muss mit einem Buchstaben beginnen
    • Er muss zwischen 3 und 255 Zeichen lang sein
    • Sie dürfen nur die folgenden Zeichen enthalten: Buchstaben [A-Za-z], Ziffern [0-9], Bindestriche -, Unterstriche _, Punkte ., Tilden ~, Pluszeichen + und Prozentzeichen %

    Sie können die Sonderzeichen in der vorherigen Liste in Ressourcennamen ohne URL-Codierung verwenden. Alle anderen Sonderzeichen müssen jedoch bei ihrer Verwendung in URLs richtig codiert oder decodiert werden. Beispielsweise ist mi-tópico eine ungültige ID. mi-t%C3%B3pico ist jedoch gültig. Dieses Format ist wichtig, wenn Sie REST-Aufrufe durchführen.

Lite-Abo erstellen

Ein Lite-Abo muss sich im selben Projekt und am selben Standort wie das Lite-Thema befinden, mit dem das Lite-Abo verknüpft ist.

Lite-Thema erstellen und verwalten

Eine Liste der verfügbaren Standorte finden Sie unter Pub/Sub Lite-Standorte.

Sie können ein Lite-Abo mit der Google Cloud Console, der Google Cloud CLI oder der Pub/Sub Lite API erstellen.

Informationen zum Erstellen eines Exportabos finden Sie unter Pub/Sub Lite-Nachrichten nach Pub/Sub exportieren.

Console

  1. Rufen Sie die Seite Lite-Abos auf.

    Lite-Abos aufrufen

  2. Klicken Sie auf Lite-Abo erstellen.

  3. Geben Sie eine Lite-Abo-ID ein.

  4. Wählen Sie ein Lite-Thema aus, von dem Nachrichten empfangen werden sollen.

  5. Wählen Sie Nachrichten sofort senden oder Nachrichten nach dem Speichern senden aus.

  6. Wählen Sie als Typ Anfangsversatz aus.

  7. Wählen Sie einen Zustellungstyp aus.

  8. Klicken Sie auf Erstellen.

gcloud

Verwenden Sie den Befehl gcloud pubsub lite-subscriptions create, um ein Lite-Abo zu erstellen:

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

Ersetzen Sie Folgendes:

  • SUBSCRIPTION_ID: die ID des Lite-Abos

  • LOCATION: der Name eines von Pub/Sub Lite unterstützten Standorts

  • TOPIC_ID: die ID des Lite-Themas, das an das Lite-Abo angehängt werden soll

  • DELIVERY_REQUIREMENT: deliver-after-stored oder deliver-immediately

Wenn die Anfrage erfolgreich ist, wird in der Befehlszeile eine Bestätigung angezeigt:

Created [SUBSCRIPTION_ID].

Protokoll

Senden Sie zum Erstellen eines Lite-Abos eine POST-Anfrage wie die folgende:

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

Ersetzen Sie Folgendes:

Geben Sie im Anfragetext die folgenden Felder an:

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

Ersetzen Sie DELIVERY_REQUIREMENT durch deliver-after-stored oder deliver-immediately.

Wenn die Anfrage erfolgreich ist, ist die Antwort das Lite-Abo im JSON-Format:

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel ausführen, folgen Sie der Einrichtungsanleitung für Go unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Java unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Python unter Pub/Sub Lite-Clientbibliotheken.

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

Nachdem Sie ein Lite-Abo für ein Lite-Thema erstellt haben, können Sie Nachrichten vom Lite-Abo empfangen.

Lite-Abo aktualisieren

Sie können Lite-Abos mit der Google Cloud Console, der Google Cloud CLI oder der Pub/Sub Lite API aktualisieren.

Console

  1. Rufen Sie die Seite Lite-Abos auf.

    Lite-Abos aufrufen

  2. Klicken Sie auf die Lite-Abo-ID.

  3. Klicken Sie auf der Seite Lite-Abonnementdetails auf Bearbeiten.

gcloud

Verwenden Sie zum Aktualisieren eines Lite-Abos den Befehl gcloud pubsub lite-subscriptions update:

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

Ersetzen Sie Folgendes:

  • SUBSCRIPTION_ID: die ID des Lite-Abos

  • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

  • DELIVERY_REQUIREMENT: deliver-after-stored oder deliver-immediately

Wenn die Anfrage erfolgreich ist, wird in der Befehlszeile das Lite-Abo angezeigt:

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

Protokoll

Um ein Lite-Abo zu aktualisieren, senden Sie eine PATCH-Anfrage wie die folgende:

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)

Ersetzen Sie Folgendes:

  • REGION: Region, in der das Lite-Abo gespeichert werden soll

  • PROJECT_NUMBER: die Projektnummer des Projekts mit dem Lite-Abo

  • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

  • SUBSCRIPTION_ID: die ID des Lite-Abos

Geben Sie im Anfragetext die folgenden Felder an:

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

Ersetzen Sie DELIVERY_REQUIREMENT durch deliver-after-stored oder deliver-immediately.

Wenn die Anfrage erfolgreich ist, ist die Antwort das Lite-Abo im JSON-Format:

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel ausführen, folgen Sie der Einrichtungsanleitung für Go unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Java unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Python unter Pub/Sub Lite-Clientbibliotheken.

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

Details zum Lite-Abo ansehen

Details zu einem Lite-Abo können Sie über die Google Cloud Console, die Google Cloud CLI oder die Pub/Sub Lite API abrufen.

Console

  1. Rufen Sie die Seite Lite-Abos auf.

    Lite-Abos aufrufen

  2. Klicken Sie auf die Lite-Abo-ID.

  3. Klicken Sie auf der Detailseite des Lite-Abos auf den Tab Details.

gcloud

Wenn Sie Details zu einem Lite-Abo abrufen möchten, verwenden Sie den Befehl gcloud pubsub lite-subscriptions describe:

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

Ersetzen Sie Folgendes:

  • SUBSCRIPTION_ID: die ID des Lite-Abos

  • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

Wenn die Anfrage erfolgreich ist, wird in der Befehlszeile das Lite-Thema angezeigt:

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

Protokoll

Wenn Sie Details zu einem Lite-Abo erhalten möchten, senden Sie eine GET-Anfrage wie die folgende:

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

Ersetzen Sie Folgendes:

  • REGION: Region, in der das Lite-Abo gespeichert werden soll

  • PROJECT_NUMBER: die Projektnummer des Projekts mit dem Lite-Abo

  • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

  • SUBSCRIPTION_ID: die ID des Lite-Abos

Wenn die Anfrage erfolgreich ist, ist die Antwort das Lite-Thema im JSON-Format:

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel ausführen, folgen Sie der Einrichtungsanleitung für Go unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Java unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Python unter Pub/Sub Lite-Clientbibliotheken.

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

Sie können die Lite-Abos in einem Projekt oder die Lite-Abos für ein Lite-Thema auflisten.

Lite-Abos in einem Projekt auflisten

Sie können Lite-Abos in einem Projekt mit der Google Cloud Console, der Google Cloud CLI oder der Pub/Sub Lite API auflisten.

Console

gcloud

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

Ersetzen Sie LOCATION durch den Namen des Standorts, an dem sich die Lite-Abos befinden.

Wenn die Anfrage erfolgreich ist, werden in der Befehlszeile die Lite-Abos angezeigt:

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

Protokoll

  • Senden Sie eine GET-Anfrage wie die folgende, um die Lite-Abos in einem Projekt aufzulisten:
GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/subscriptions
Authorization: Bearer $(gcloud auth print-access-token)

Ersetzen Sie Folgendes:

  • REGION: Region, in der das Lite-Abo gespeichert werden soll

  • PROJECT_NUMBER: die Projektnummer des Projekts mit dem Lite-Abo

Wenn die Anfrage erfolgreich ist, ist die Antwort das Lite-Thema im JSON-Format:

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel ausführen, folgen Sie der Einrichtungsanleitung für Go unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Java unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Python unter Pub/Sub Lite-Clientbibliotheken.

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-Abos für ein Lite-Thema auflisten

Sie können Lite-Abos für ein Lite-Thema mithilfe der Google Cloud Console, der Google Cloud CLI oder der Pub/Sub Lite API auflisten.

Console

  1. Rufen Sie die Seite Lite-Themen auf.

    Lite-Themen aufrufen

  2. Eine Lite-Themen-ID auswählen.

  3. Auf der Detailseite Lite-Themen enthält der Abschnitt Lite-Abos eine Liste der Lite-Abos für das Lite-Thema.

gcloud

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

Ersetzen Sie Folgendes:

  • TOPIC_ID: die ID des Lite-Themas, mit dem die Lite-Abos verknüpft sind

  • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

Wenn die Anfrage erfolgreich ist, werden in der Befehlszeile die Lite-Abos angezeigt:

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

Protokoll

  • Um die Lite-Abos für ein Lite-Thema aufzulisten, senden Sie eine GET-Anfrage wie die folgende:
GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/lite-topics/TOPIC_ID/subscriptions
Authorization: Bearer $(gcloud auth print-access-token)

Ersetzen Sie Folgendes:

  • REGION: Region, in der das Lite-Abo gespeichert werden soll

  • PROJECT_NUMBER: die Projektnummer des Projekts mit dem Lite-Abo

  • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

  • TOPIC_ID: die ID des Lite-Themas, mit dem die Lite-Abos verknüpft sind

Wenn die Anfrage erfolgreich ist, ist die Antwort eine Liste von Lite-Abos im JSON-Format:

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

Einfach loslegen (Go)

Bevor Sie dieses Beispiel ausführen, folgen Sie der Einrichtungsanleitung für Go unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Java unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Python unter Pub/Sub Lite-Clientbibliotheken.

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-Abo löschen

Sie können Lite-Abos mit der Google Cloud Console, der Google Cloud CLI oder der Pub/Sub Lite API löschen.

Console

  1. Rufen Sie die Seite Lite-Abos auf.

    Lite-Abos aufrufen

  2. Klicken Sie auf die Lite-Abo-ID.

  3. Klicken Sie auf der Seite Lite-Abonnementdetails auf Löschen.

  4. Klicken Sie im angezeigten Dialogfeld auf Löschen, um zu bestätigen, dass Sie das Lite-Abo löschen möchten.

gcloud

Verwenden Sie zum Löschen eines Lite-Abos den Befehl gcloud pubsub lite-subscriptions delete:

  1. Führen Sie den Befehl delete aus:

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

    Ersetzen Sie Folgendes:

    • SUBSCRIPTION_ID: die ID des Lite-Abos

    • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

  2. Zum Bestätigen geben Sie "Y" ein.

Wenn die Anfrage erfolgreich ist, wird in der Befehlszeile eine Bestätigung angezeigt:

Deleted subscription [SUBSCRIPTION_ID].

Protokoll

  • Um ein Lite-Thema zu löschen, senden Sie eine DELETE-Anfrage wie die folgende:
DELETE https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

Ersetzen Sie Folgendes:

  • REGION: Region, in der das Lite-Abo gespeichert werden soll

  • PROJECT_NUMBER: die Projektnummer des Projekts mit dem Lite-Abo

  • LOCATION: der Name des Standorts, an dem sich das Lite-Abo befindet

  • SUBSCRIPTION_ID: die ID des Lite-Abos

Wenn die Anfrage erfolgreich ist, ist die Antwort ein leeres JSON-Objekt.

Einfach loslegen (Go)

Bevor Sie dieses Beispiel ausführen, folgen Sie der Einrichtungsanleitung für Go unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Java unter Pub/Sub Lite-Clientbibliotheken.

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

Bevor Sie dieses Beispiel ausführen, folgen Sie der Anleitung zur Einrichtung von Python unter Pub/Sub Lite-Clientbibliotheken.

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

Weitere Informationen