Creare e gestire argomenti Lite

Questo documento spiega come creare, visualizzare ed eliminare un argomento Pub/Sub Lite.

Panoramica di un argomento Lite

Un servizio Pub/Sub Lite richiede un argomento a cui gli editori possono inviare messaggi in modo che i sottoscrittori possano riceverli. In Pub/Sub Lite, puoi scegliere di creare un argomento Lite a livello di zona o di regione.

Un argomento Lite a livello di zona e un argomento Lite a livello di regione differiscono solo per il modo in cui replicano i dati. Tutte le altre proprietà dell'argomento sono le stesse descritte in una sezione successiva di questo documento.

Replica dei dati in un argomento Lite

Gli argomenti regionali Pub/Sub Lite archiviano i dati in due zone di un'unica regione. Gli argomenti di zona Pub/Sub Lite replicano i dati all'interno di una sola zona. Pub/Sub Lite replica i dati in modo asincrono.

La disponibilità di Pub/Sub Lite dipende dalla disponibilità dei componenti sottostanti, che includono sia il frontend dell'applicazione sia l'archiviazione.

La disponibilità di un argomento a livello di zona Pub/Sub Lite dipende dalla disponibilità sia del frontend dell'applicazione sia dello spazio di archiviazione nella zona configurata. Se si verifica un errore a livello di zona per il frontend o lo spazio di archiviazione dell'applicazione, l'argomento Lite a livello di zona diventa non disponibile per la durata dell'interruzione.

La disponibilità di un argomento a livello di regione Pub/Sub Lite dipende dalla disponibilità del frontend e dello spazio di archiviazione dell'applicazione nella regione configurata. Ecco i possibili tipi di errore:

  • Se l'archiviazione frontend o dell'applicazione riscontra un errore a livello di zona, l'argomento Lite a livello di regione rimane disponibile.

  • Se sia il frontend dell'applicazione sia lo spazio di archiviazione riscontrano un errore a livello di zona, l'argomento Lite a livello di regione rimane disponibile, purché entrambi i componenti non inizino a presentare errori contemporaneamente.

  • Se sia il frontend dell'applicazione che l'archiviazione non riescono contemporaneamente, l'argomento Lite a livello di regione rimane non disponibile per la durata dell'interruzione. Durante questo periodo, i client potrebbero non riuscire a pubblicare o utilizzare i messaggi, ma i messaggi vengono comunque recapitati nell'ordine corretto.

Un argomento Lite a livello di regione fornisce protezione dalla maggior parte dei tipi di errori a zona singola. Tuttavia, in alcuni rari casi, la natura asincrona della replica può causare un errore simultaneo di più componenti in una singola zona. Di conseguenza, un argomento Lite a livello di regione non è più disponibile.

Proprietà di un argomento Lite

Gli argomenti Lite hanno le seguenti proprietà:

  • Numero di partizioni. Una partizione è l'unità base di parallelismo in Pub/Sub Lite. Un argomento Lite può avere una o più partizioni.

  • Capacità di una partizione. La capacità di una partizione è descritta dalle tre proprietà seguenti:

    • Velocità effettiva di pubblicazione (MiBps). La frequenza massima con cui puoi pubblicare messaggi.

    • Velocità effettiva sottoscrizione (MiBps). La frequenza massima con cui i messaggi vengono inoltrati alle sottoscrizioni Lite.

    • Spazio di archiviazione (GiB). La dimensione massima dei messaggi nella partizione. La capacità configurabile minima di una partizione è 30 GiB.

  • Capacità di archiviazione di un argomento Lite. Tutte le partizioni di un argomento Lite hanno la stessa capacità di archiviazione configurata. La capacità di archiviazione totale di un argomento Lite è la somma della capacità di archiviazione di tutte le partizioni dell'argomento. Ad esempio, se un argomento Lite ha 8 partizioni e ogni partizione ha una dimensione di 30 GiB, la capacità di archiviazione totale dell'argomento Lite è 240 GiB (8 x 30).

  • Capacità di velocità effettiva di un argomento Lite. La capacità di velocità effettiva è composta dalla capacità totale di velocità effettiva di pubblicazione e sottoscrizione di tutte le partizioni nell'argomento Lite. Anche se hai un argomento che, in forma aggregata, può supportare 1 GiBps di velocità effettiva di pubblicazione, è il limite di pubblicazione per partizione che limita efficacemente la velocità effettiva.

  • Limite di client abbonati e abbonamenti. Pub/Sub Lite supporta un client con sottoscrittore singolo per una partizione e una sottoscrizione singola. Ad esempio, una sottoscrizione a un argomento con 5 partizioni può avere al massimo 5 client sottoscrittori che utilizzano i relativi messaggi. Se sono configurati più client abbonati, i client in eccesso rimangono inattivi. Lo stesso argomento con 2 abbonamenti può avere fino a 10 client abbonato, 5 client per ogni abbonamento.

  • Prenotazioni. La prenotazione è il modo più semplice per eseguire il provisioning e gestire la capacità effettiva per vari argomenti. Il provisioning della capacità di velocità effettiva con prenotazioni è obbligatorio per gli argomenti Lite a livello di regione ed è facoltativo per gli argomenti Lite a livello di zona.

    Se non utilizzi le prenotazioni per un argomento Lite a livello di zona, devi eseguire esplicitamente il provisioning della capacità di velocità effettiva di pubblicazione e sottoscrizione dell'argomento. Senza una prenotazione, tutte le partizioni in un argomento Lite hanno la stessa capacità di velocità effettiva configurata. Per saperne di più, consulta Configurare la capacità di velocità effettiva senza prenotazioni.

  • Configurazione dello spazio di archiviazione. Per configurare l'archiviazione, devi specificare sia la capacità di archiviazione sia, facoltativamente, il periodo di conservazione dei messaggi.

    • Periodo di conservazione dei messaggi. La quantità massima di tempo per cui un argomento Lite archivia i messaggi. Se non specifichi un periodo di conservazione dei messaggi, l'argomento Lite archivia i messaggi finché non superi la capacità di archiviazione.

    • Capacità dello spazio di archiviazione. La capacità dell'argomento Pub/Sub Lite è determinata dal numero di partizioni nell'argomento e dalla capacità di archiviazione di ogni partizione. Lo spazio di archiviazione per partizione è la quantità di spazio di archiviazione, in byte, per ogni partizione. Gli argomenti Lite a livello di regione utilizzano due byte di capacità di archiviazione per ogni byte pubblicato. Gli argomenti Lite a livello di zona utilizzano un byte di capacità di archiviazione per ogni byte pubblicato.

    Se superi la capacità di archiviazione, il servizio Pub/Sub Lite continua a pubblicare messaggi. Tuttavia, per creare più spazio di archiviazione, i messaggi meno recenti della partizione vengono eliminati. L'eliminazione dei messaggi meno recenti avviene anche se si trovano nel periodo di conservazione dei messaggi. Il servizio non elimina mai i messaggi prima della scadenza del relativo TTL, a meno che la loro rimozione non sia necessaria per fare spazio ai nuovi messaggi pubblicati. Per informazioni su come la capacità è correlata ai prezzi, consulta la pagina relativa ai prezzi di Pub/Sub Lite.

Linee guida per assegnare un nome a un argomento

Il nome di una risorsa Pub/Sub Lite identifica in modo univoco una risorsa Pub/Sub Lite, ad esempio un argomento, una sottoscrizione o una prenotazione. Il nome della risorsa deve rientrare nel formato seguente:

projects/project-identifier/collection/ID

  • project-identifier: deve essere l'ID o il numero del progetto, disponibile nella console Google Cloud. Ad esempio, my-cool-project è un ID progetto. 123456789123 è un numero di progetto.

  • collection: deve essere topics, subscriptions o reservations.

  • ID: deve essere conforme alle seguenti linee guida:

    • Non iniziare con la stringa goog
    • Inizia con una lettera
    • Contiene tra 3 e 255 caratteri
    • Contenere solo i seguenti caratteri: lettere [A-Za-z], numeri [0-9], trattini -, trattini bassi _, punti ., tilde ~, segni più + e segni di percentuale %

    Puoi utilizzare i caratteri speciali nell'elenco precedente nei nomi delle risorse senza codifica URL. Tuttavia, devi assicurarti che tutti gli altri caratteri speciali siano codificati o decodificati correttamente quando li utilizzi negli URL. Ad esempio, mi-tópico è un ID non valido. Tuttavia, mi-t%C3%B3pico è valido. Questo formato è importante quando effettui chiamate REST.

Aumenta la capacità di velocità effettiva di un argomento Lite

Se non utilizzi le prenotazioni Lite, puoi impostare la capacità di velocità effettiva di ogni partizione di qualsiasi argomento Lite a livello di zona su un valore impostato in base ai seguenti limiti:

  • Velocità effettiva di pubblicazione compresa tra 4 e 16 MiBps

  • Velocità effettiva di sottoscrizione compresa tra 4 e 32 MiBps

Questi limiti si applicano anche alle partizioni associate a una prenotazione Lite. Con le prenotazioni, ogni partizione può consumare qualsiasi capacità di velocità effettiva entro i limiti specificati, a condizione che non venga superata la capacità totale della prenotazione. Facoltativamente, puoi impostare un limite inferiore per la velocità effettiva effettiva per partizione, in modo da rendere il traffico più prevedibile.

Puoi aumentare il numero di partizioni in un argomento per scalarlo orizzontalmente. Il numero di partizioni in un argomento non può essere ridotto.

Quando modifichi il numero di partizioni, l'ordine relativo dei messaggi non viene conservato. Internamente, i messaggi vengono assegnati alle partizioni utilizzando una funzione hash. L'aggiornamento del numero di partizioni in un argomento modifica questa funzione hash. È probabile che i messaggi con la stessa chiave pubblicati dopo l'aggiornamento del conteggio delle partizioni vengano mappati su una partizione diversa da quella pubblicata prima dell'aggiornamento.

Inoltre, il ridimensionamento dell'argomento richiede alcuni secondi per la propagazione a tutti gli editori. C'è un breve periodo di tempo in cui alcuni editori usano la nuova funzione di hash e altri ancora usano la vecchia.

Aumentare la capacità di archiviazione di un argomento Lite

Puoi aumentare o diminuire la quantità di spazio di archiviazione in un argomento Lite. L'argomento Lite esegue il provisioning della stessa quantità di spazio di archiviazione a ogni partizione. Se aumenti lo spazio di archiviazione a 60 GiB, ciascuna partizione riceve 60 GiB di spazio di archiviazione.

Se diminuisci la quantità di spazio di archiviazione in un argomento Lite, il servizio Pub/Sub Lite rimuove prima i messaggi meno recenti.

Per informazioni su come la capacità è correlata ai prezzi, consulta i prezzi di Pub/Sub Lite

crea un argomento Lite

Puoi creare argomenti Lite con la console Google Cloud, Google Cloud CLI o l'API Pub/Sub Lite.

Per un elenco delle regioni e delle zone disponibili, consulta Località di Pub/Sub Lite.

Console

  1. Vai alla pagina Argomenti Lite.

    Vai agli argomenti Lite

  2. Fai clic su Crea argomento Lite.

    1. Per creare un argomento Lite a livello di zona, seleziona una regione e una zona all'interno della regione.

    2. Per creare un argomento Lite a livello di regione, seleziona una regione.

    Non puoi aggiornare la località dopo la creazione di un argomento.

  3. Nella sezione Nome, inserisci un ID argomento Lite.

    Il nome dell'argomento Lite include l'ID dell'argomento Lite, la località e il numero del progetto.

  4. Nella sezione Velocità effettiva:

    1. Seleziona o crea una prenotazione.

      Questo passaggio è facoltativo per un argomento Lite a livello di zona e obbligatorio per un argomento Lite a livello di regione.

    2. Inserisci la velocità effettiva di pubblicazione massima e la velocità effettiva di sottoscrizione massima.

      Alcune partizioni vengono impostate automaticamente in base ai tuoi input. Puoi modificare questo numero dopo aver salvato l'argomento.

  5. Nella sezione Archiviazione dei messaggi:

    1. Inserisci lo spazio di archiviazione per partizione.

    2. Seleziona una delle due opzioni per il periodo di conservazione dei messaggi.

  6. Esamina le modifiche e fai clic su Crea.

gcloud

Per creare un argomento Lite, utilizza il comando gcloud pubsub lite-topics create:

gcloud pubsub lite-topics create TOPIC_ID \
  --location=LOCATION \
  --partitions=NUMBER_OF_PARTITIONS \
  --per-partition-bytes=STORAGE_PER_PARTITION \
  [--throughput-reservation=RESERVATION_NAME \]
  [--message-retention-period=MESSAGE_RETENTION_PERIOD]

Sostituisci quanto segue:

  • TOPIC_ID: l'ID dell'argomento Lite

  • LOCATION: il nome di una località supportata da Pub/Sub Lite

  • NUMBER_OF_PARTITIONS: un numero intero per il numero di partizioni nell'argomento Lite

  • STORAGE_PER_PARTITION: la quantità di spazio di archiviazione per ogni partizione, ad esempio 30GiB

  • RESERVATION_NAME: il percorso completo di una prenotazione Lite come projects/123456789/locations/us-west1/reservations/my-reservation

  • MESSAGE_RETENTION_PERIOD: per quanto tempo l'argomento Lite archivia i messaggi, ad esempio 1d o 2w

Se la richiesta ha esito positivo, la riga di comando visualizza un messaggio di conferma:

Created [TOPIC_ID].

Protocollo

Per creare un argomento Lite, invia una richiesta POST come la seguente:

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

Sostituisci quanto segue:

Specifica i seguenti campi nel corpo della richiesta:

{
  "partitionConfig": {
       "count": NUMBER_OF_PARTITIONS,
       "capacity": {
         "publishMibPerSec": publish_CAPACITY,
         "subscribeMibPerSec": subscribe_CAPACITY,
       }
  },
  "retentionConfig": {
       "perPartitionBytes": STORAGE_PER_PARTITION,
       "period": MESSAGE_RETENTION_PERIOD,
  },
  "reservationConfig": {
       "throughputReservation": RESERVATION_NAME
  }
}

Sostituisci quanto segue:

  • NUMBER_OF_PARTITIONS: un numero intero per il numero di partizioni nell'argomento Lite

  • STORAGE_PER_PARTITION: la quantità di spazio di archiviazione per ogni partizione, ad esempio 30GiB

  • publish_CAPACITY: un numero intero per la capacità di velocità effettiva di pubblicazione di ogni partizione

  • subscribe_CAPACITY: un numero intero per la capacità di velocità effettiva di sottoscrizione di ogni partizione

  • MESSAGE_RETENTION_PERIOD: per quanto tempo l'argomento Lite archivia i messaggi, ad esempio 1d o 2w

  • RESERVATION_NAME: il percorso completo di una prenotazione Lite come projects/123456789/locations/us-west1/reservations/my-reservation

Se la richiesta ha esito positivo, la risposta sarà l'argomento Lite in formato JSON:

{
  "name": projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID,
  "partitionConfig": {
       "count": NUMBER_OF_PARTITIONS,
       "capacity": {
         "publishMibPerSec": publish_CAPACITY,
         "subscribeMibPerSec": subscribe_CAPACITY,
       }
  },
  "retentionConfig": {
       "perPartitionBytes": STORAGE_PER_PARTITION,
       "period": MESSAGE_RETENTION_PERIOD,
  },
  "reservationConfig": {
       "throughputReservation": RESERVATION_NAME
  }
}

Go

Prima di eseguire questo esempio, segui le istruzioni per la configurazione di Go in Librerie client di Pub/Sub Lite.

import (
	"context"
	"fmt"
	"io"

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

func createTopic(w io.Writer, projectID, region, location, topicID, reservation string) error {
	// projectID := "my-project-id"
	// region := "us-central1" // see https://cloud.google.com/pubsub/lite/docs/locations
	// 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"
	// topicID := "my-topic"
	// reservation := "projects/my-project-id/reservations/my-reservation"
	ctx := context.Background()
	client, err := pubsublite.NewAdminClient(ctx, region)
	if err != nil {
		return fmt.Errorf("pubsublite.NewAdminClient: %w", err)
	}
	defer client.Close()

	const gib = 1 << 30

	topicPath := fmt.Sprintf("projects/%s/locations/%s/topics/%s", projectID, location, topicID)
	// For ranges of fields in TopicConfig, see https://pkg.go.dev/cloud.google.com/go/pubsublite/#TopicConfig
	topic, err := client.CreateTopic(ctx, pubsublite.TopicConfig{
		Name:                       topicPath,
		PartitionCount:             2, // Must be >= 1 and cannot decrease after creation.
		PublishCapacityMiBPerSec:   4,
		SubscribeCapacityMiBPerSec: 8,
		PerPartitionBytes:          30 * gib,
		RetentionDuration:          pubsublite.InfiniteRetention,
		ThroughputReservation:      reservation,
	})
	if err != nil {
		return fmt.Errorf("client.CreateTopic got err: %w", err)
	}
	fmt.Fprintf(w, "Created topic: %#v\n", topic)
	return nil
}

Java

Prima di eseguire questo esempio, segui le istruzioni di configurazione Java in Librerie client di 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.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.ReservationName;
import com.google.cloud.pubsublite.ReservationPath;
import com.google.cloud.pubsublite.TopicName;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.proto.Topic;
import com.google.cloud.pubsublite.proto.Topic.PartitionConfig;
import com.google.cloud.pubsublite.proto.Topic.PartitionConfig.Capacity;
import com.google.cloud.pubsublite.proto.Topic.ReservationConfig;
import com.google.cloud.pubsublite.proto.Topic.RetentionConfig;
import com.google.protobuf.util.Durations;
import java.util.concurrent.ExecutionException;

public class CreateTopicExample {

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

    createTopicExample(
        cloudRegion, zoneId, projectNumber, topicId, reservationId, partitions, regional);
  }

  public static void createTopicExample(
      String cloudRegion,
      char zoneId,
      long projectNumber,
      String topicId,
      String reservationId,
      int partitions,
      boolean regional)
      throws Exception {

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

    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();

    Topic topic =
        Topic.newBuilder()
            .setPartitionConfig(
                PartitionConfig.newBuilder()
                    // Set throughput capacity per partition in MiB/s.
                    .setCapacity(
                        Capacity.newBuilder()
                            // Must be 4-16 MiB/s.
                            .setPublishMibPerSec(4)
                            // Must be 4-32 MiB/s.
                            .setSubscribeMibPerSec(8)
                            .build())
                    .setCount(partitions))
            .setRetentionConfig(
                RetentionConfig.newBuilder()
                    // How long messages are retained.
                    .setPeriod(Durations.fromDays(1))
                    // Set storage per partition to 30 GiB. This must be 30 GiB-10 TiB.
                    // If the number of bytes stored in any of the topic's partitions grows
                    // beyond this value, older messages will be dropped to make room for
                    // newer ones, regardless of the value of `period`.
                    .setPerPartitionBytes(30 * 1024 * 1024 * 1024L))
            .setReservationConfig(
                ReservationConfig.newBuilder()
                    .setThroughputReservation(reservationPath.toString())
                    .build())
            .setName(topicPath.toString())
            .build();

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

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Topic response = adminClient.createTopic(topic).get();
      if (regional) {
        System.out.println(response.getAllFields() + " (regional topic) created successfully.");
      } else {
        System.out.println(response.getAllFields() + " (zonal topic) created successfully.");
      }
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (AlreadyExistsException alreadyExists) {
        System.out.println("This topic already exists.");
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
  }
}

Python

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Python in Librerie client di Pub/Sub Lite.

from google.api_core.exceptions import AlreadyExists
from google.cloud.pubsublite import AdminClient, Topic
from google.cloud.pubsublite.types import (
    CloudRegion,
    CloudZone,
    ReservationPath,
    TopicPath,
)
from google.protobuf.duration_pb2 import Duration

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

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

topic_path = None
if regional:
    #  A regional topic.
    topic_path = TopicPath(project_number, cloud_region, topic_id)
else:
    #  A zonal topic
    topic_path = TopicPath(
        project_number, CloudZone(cloud_region, zone_id), topic_id
    )

topic = Topic(
    name=str(topic_path),
    partition_config=Topic.PartitionConfig(
        # A topic must have at least one partition.
        count=num_partitions,
        # Set throughput capacity per partition in MiB/s.
        capacity=Topic.PartitionConfig.Capacity(
            # Set publish throughput capacity per partition to 4 MiB/s. Must be >= 4 and <= 16.
            publish_mib_per_sec=4,
            # Set subscribe throughput capacity per partition to 4 MiB/s. Must be >= 4 and <= 32.
            subscribe_mib_per_sec=8,
        ),
    ),
    retention_config=Topic.RetentionConfig(
        # Set storage per partition to 30 GiB. This must be in the range 30 GiB-10TiB.
        # If the number of byptes stored in any of the topic's partitions grows beyond
        # this value, older messages will be dropped to make room for newer ones,
        # regardless of the value of `period`.
        per_partition_bytes=30 * 1024 * 1024 * 1024,
        # Allow messages to be retained for 7 days.
        period=Duration(seconds=60 * 60 * 24 * 7),
    ),
    reservation_config=Topic.ReservationConfig(
        throughput_reservation=str(reservation_path),
    ),
)

client = AdminClient(cloud_region)
try:
    response = client.create_topic(topic)
    if regional:
        print(f"{response.name} (regional topic) created successfully.")
    else:
        print(f"{response.name} (zonal topic) created successfully.")
except AlreadyExists:
    print(f"{topic_path} already exists.")

Dopo aver creato l'argomento Lite, puoi scalare la velocità effettiva e la capacità di archiviazione per partizione. Puoi anche aumentare, ma non diminuire, il numero di partizioni.

Aggiorna un argomento Lite

Puoi aggiornare le seguenti proprietà di un argomento Lite:

  • La prenotazione associata all'argomento Lite

  • Il numero di partizioni nell'argomento (può solo essere aumentato)

  • I limiti di capacità per la velocità effettiva di pubblicazione e sottoscrizione

  • Lo spazio di archiviazione per partizione

  • Il tipo di conservazione dei messaggi

Prima di scalare la capacità di velocità effettiva o la capacità di archiviazione di un argomento, consulta Scalare la capacità di velocità effettiva e Scalare la capacità di archiviazione.

Puoi aggiornare un argomento Lite con la console Google Cloud, Google Cloud CLI o l'API Pub/Sub Lite.

Console

  1. Vai alla pagina Argomenti Lite.

    Vai agli argomenti Lite

  2. Fai clic sull'ID dell'argomento Lite.

  3. Fai clic su Modifica.

  4. Puoi apportare uno o tutti i seguenti aggiornamenti:

    • Utilizza un'altra prenotazione. Per gli argomenti a livello di zona, puoi scegliere di non utilizzare una prenotazione.
    • Inserisci il numero di partizioni. Questo valore può essere aumentato, ma non diminuito.
    • Abilita o disabilita la velocità effettiva massima di pubblicazione e sottoscrizione consentita.
    • Per gli argomenti a livello di zona, aggiorna la velocità effettiva di pubblicazione e sottoscrizione prenotata. Per gli argomenti a cui è collegata una prenotazione, la velocità effettiva aggiornata riflette il nuovo limite massimo.
    • Modifica la capacità di archiviazione per partizione.
    • Modifica il periodo di conservazione dei messaggi.
  5. Fai clic su Update (Aggiorna).

gcloud

Per aggiornare un argomento Lite, utilizza il comando gcloud pubsub lite-topics update:

gcloud pubsub lite-topics update TOPIC_ID \
  --location=LOCATION \
  --partitions=NUMBER_OF_PARTITIONS \
  --per-partition-publish-mib=publish_CAPACITY \
  --per-partition-subscribe-mib=subscribe_CAPACITY \
  --per-partition-bytes=STORAGE_PER_PARTITION \
  --message-retention-period=MESSAGE_RETENTION_PERIOD

Sostituisci quanto segue:

  • TOPIC_ID: l'ID dell'argomento Lite

  • LOCATION: il nome della posizione in cui si trova l'argomento Lite

  • NUMBER_OF_PARTITIONS: il numero di partizioni da configurare per l'argomento Lite.

  • publish_CAPACITY: un numero intero per la capacità di velocità effettiva di pubblicazione di ogni partizione

  • subscribe_CAPACITY: un numero intero per la capacità di velocità effettiva di sottoscrizione di ogni partizione

  • STORAGE_PER_PARTITION: la quantità di spazio di archiviazione per ogni partizione, ad esempio 30GiB

  • MESSAGE_RETENTION_PERIOD: per quanto tempo l'argomento Lite archivia i messaggi, ad esempio 1d o 2w

Se la richiesta ha esito positivo, la riga di comando visualizza l'argomento Lite:

name: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
partitionConfig:
  count: NUMBER_OF_PARTITIONS
  capacity:
    publishMibPerSec: publish_CAPACITY
    subscribeMibPerSec: subscribe_CAPACITY
retentionConfig:
  perPartitionBytes: STORAGE_PER_PARTITION
  period: MESSAGE_RETENTION_PERIOD

Protocollo

Per aggiornare un argomento Lite, invia una richiesta PATCH come la seguente:

PATCH https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID?updateMask=partitionConfig.capacity,retentionConfig.perPartitionBytes,retentionConfig.period,partitionConfig.count
Authorization: Bearer $(gcloud auth print-access-token)

Sostituisci quanto segue:

  • REGION: la regione in cui si trova l'argomento Lite

  • PROJECT_NUMBER: il numero del progetto con l'argomento Lite

  • LOCATION: il nome della posizione in cui si trova l'argomento Lite

  • TOPIC_ID: l'ID dell'argomento Lite

Specifica i seguenti campi nel corpo della richiesta:

{
  "partitionConfig": {
      "count": NUMBER_OF_PARTITIONS,
      "capacity": {
         "publishMibPerSec": publish_CAPACITY,
         "subscribeMibPerSec": subscribe_CAPACITY,
      }
   },
   "retentionConfig": {
       "perPartitionBytes": STORAGE_PER_PARTITION,
       "period": MESSAGE_RETENTION_PERIOD,
   },
}

Sostituisci quanto segue:

  • publish_CAPACITY: un numero intero per la capacità di velocità effettiva di pubblicazione di ogni partizione

  • subscribe_CAPACITY: un numero intero per la capacità di velocità effettiva di sottoscrizione di ogni partizione

  • STORAGE_PER_PARTITION: la quantità di spazio di archiviazione per ogni partizione, ad esempio 30GiB

  • MESSAGE_RETENTION_PERIOD: per quanto tempo l'argomento Lite archivia i messaggi, ad esempio 1d o 2w

  • NUMBER_OF_PARTITIONS: il numero di partizioni da configurare per l'argomento Lite.

Se la richiesta ha esito positivo, la risposta sarà l'argomento Lite in formato JSON:

{
  "name": projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID,
  "partitionConfig": {
      "count": NUMBER_OF_PARTITIONS,
      "capacity": {
         "publishMibPerSec": publish_CAPACITY,
         "subscribeMibPerSec": subscribe_CAPACITY,
      }
   },
   "retentionConfig": {
       "perPartitionBytes": STORAGE_PER_PARTITION,
       "period": MESSAGE_RETENTION_PERIOD,
   },
}

Go

Prima di eseguire questo esempio, segui le istruzioni per la configurazione di Go in Librerie client di Pub/Sub Lite.

import (
	"context"
	"fmt"
	"io"
	"time"

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

func updateTopic(w io.Writer, projectID, region, location, topicID, reservation 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"
	// topicID := "my-topic"
	// reservation := "projects/my-project-id/reservations/my-reservation"
	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)
	// For ranges of fields in TopicConfigToUpdate, see https://pkg.go.dev/cloud.google.com/go/pubsublite/#TopicConfigToUpdate
	config := pubsublite.TopicConfigToUpdate{
		Name:                       topicPath,
		PartitionCount:             3, // Partition count cannot decrease.
		PublishCapacityMiBPerSec:   8,
		SubscribeCapacityMiBPerSec: 16,
		PerPartitionBytes:          60 * 1024 * 1024 * 1024,
		RetentionDuration:          24 * time.Hour,
		ThroughputReservation:      reservation,
	}
	updatedCfg, err := client.UpdateTopic(ctx, config)
	if err != nil {
		return fmt.Errorf("client.UpdateTopic got err: %w", err)
	}
	fmt.Fprintf(w, "Updated topic: %v\n", updatedCfg)
	return nil
}

Java

Prima di eseguire questo esempio, segui le istruzioni di configurazione Java in Librerie client di 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.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.ReservationName;
import com.google.cloud.pubsublite.ReservationPath;
import com.google.cloud.pubsublite.TopicName;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.proto.Topic;
import com.google.cloud.pubsublite.proto.Topic.PartitionConfig;
import com.google.cloud.pubsublite.proto.Topic.PartitionConfig.Capacity;
import com.google.cloud.pubsublite.proto.Topic.ReservationConfig;
import com.google.cloud.pubsublite.proto.Topic.RetentionConfig;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.Durations;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;

public class UpdateTopicExample {

  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 reservationId = "your-reservation-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 = true;

    updateTopicExample(cloudRegion, zoneId, projectNumber, topicId, reservationId, regional);
  }

  public static void updateTopicExample(
      String cloudRegion,
      char zoneId,
      long projectNumber,
      String topicId,
      String reservationId,
      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();

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

    Iterable<String> iterablePaths =
        Arrays.asList(
            "partition_config.scale",
            "retention_config.per_partition_bytes",
            "retention_config.period",
            "reservation_config.throughput_reservation");

    FieldMask fieldMask = FieldMask.newBuilder().addAllPaths(iterablePaths).build();

    Topic topic =
        Topic.newBuilder()
            .setPartitionConfig(
                PartitionConfig.newBuilder()
                    .setCapacity(
                        Capacity.newBuilder()
                            .setPublishMibPerSec(16)
                            .setSubscribeMibPerSec(32)
                            .build())
                    .build())
            .setRetentionConfig(
                RetentionConfig.newBuilder()
                    // Set storage per partition to 32 GiB. This must be 30 GiB-10 TiB.
                    // If the number of bytes stored in any of the topic's partitions grows
                    // beyond this value, older messages will be dropped to make room for
                    // newer ones, regardless of the value of `period`.
                    // Be careful when decreasing storage per partition as it may cause
                    // lost messages.
                    .setPerPartitionBytes(32 * 1024 * 1024 * 1024L)
                    .setPeriod(Durations.fromDays(7)))
            .setReservationConfig(
                ReservationConfig.newBuilder()
                    .setThroughputReservation(reservationPath.toString())
                    .build())
            .setName(topicPath.toString())
            .build();

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

    try (AdminClient adminClient = AdminClient.create(adminClientSettings)) {
      Topic topicBeforeUpdate = adminClient.getTopic(topicPath).get();
      System.out.println("Before update: " + topicBeforeUpdate.getAllFields());

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

Python

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Python in Librerie client di Pub/Sub Lite.

from google.api_core.exceptions import NotFound
from google.cloud.pubsublite import AdminClient, Topic
from google.cloud.pubsublite.types import (
    CloudRegion,
    CloudZone,
    ReservationPath,
    TopicPath,
)
from google.protobuf.duration_pb2 import Duration
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"
# reservation_id = "your-reservation-id"
# regional = True

location = None
if regional:
    #  A region.
    location = CloudRegion(cloud_region)
else:
    #  A zone.
    location = CloudZone(CloudRegion(cloud_region), zone_id)

topic_path = TopicPath(project_number, location, topic_id)
reservation_path = ReservationPath(project_number, cloud_region, reservation_id)

# Defines which topic fields to update.
field_mask = FieldMask(
    paths=[
        "partition_config.capacity",
        "retention_config.per_partition_bytes",
        "retention_config.period",
        "reservation_confing.throughput_reservation",
    ]
)

# Defines how to update the topic fields.
topic = Topic(
    name=str(topic_path),
    partition_config=Topic.PartitionConfig(
        capacity=Topic.PartitionConfig.Capacity(
            publish_mib_per_sec=16,
            subscribe_mib_per_sec=32,
        )
    ),
    retention_config=Topic.RetentionConfig(
        # Set storage per partition to 32 GiB. This must be in the range 30 GiB-10TiB.
        # If the number of byptes stored in any of the topic's partitions grows beyond
        # this value, older messages will be dropped to make room for newer ones,
        # regardless of the value of `period`.
        # Be careful when decreasing storage per partition as it may cuase lost messages.
        per_partition_bytes=32 * 1024 * 1024 * 1024,
        # Allow messages to be stored for 14 days.
        period=Duration(seconds=60 * 60 * 24 * 14),
    ),
    reservation_config=Topic.ReservationConfig(
        throughput_reservation=str(reservation_path),
    ),
)

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

Visualizza i dettagli dell'argomento Lite

Puoi ottenere dettagli su un argomento Lite utilizzando la console Google Cloud, Google Cloud CLI o l'API Pub/Sub Lite.

Console

  1. Vai alla pagina Argomenti Lite.

    Vai agli argomenti Lite

  2. Fai clic sull'ID dell'argomento Lite.

gcloud

Per ottenere dettagli su un argomento Lite, utilizza il comando gcloud pubsub lite-topics describe:

gcloud pubsub lite-topics describe TOPIC_ID \
--location=LOCATION

Sostituisci quanto segue:

  • TOPIC_ID: l'ID dell'argomento Lite

  • LOCATION: il nome della posizione in cui si trova l'argomento Lite

Se la richiesta ha esito positivo, la riga di comando visualizza l'argomento Lite:

name: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
partitionConfig:
  count: NUMBER_OF_PARTITIONS
  capacity:
    publishMibPerSec: publish_CAPACITY
    subscribeMibPerSec: subscribe_CAPACITY
retentionConfig:
  perPartitionBytes: STORAGE_PER_PARTITION
  period: MESSAGE_RETENTION_PERIOD

Protocollo

Per ottenere dettagli su un argomento Lite, invia una richiesta GET come la seguente:

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

Sostituisci quanto segue:

  • REGION: la regione in cui si trova l'argomento Lite

  • PROJECT_NUMBER: il numero del progetto con l'argomento Lite

  • LOCATION: il nome della posizione in cui si trova l'argomento Lite

  • TOPIC_ID: l'ID dell'argomento Lite

Se la richiesta ha esito positivo, la risposta sarà l'argomento Lite in formato JSON:

{
  "name": projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID,
  "partitionConfig": {
      "count": NUMBER_OF_PARTITIONS,
      "capacity": {
         "publishMibPerSec": publish_CAPACITY,
         "subscribeMibPerSec": subscribe_CAPACITY,
      }
   },
   "retentionConfig": {
       "perPartitionBytes": STORAGE_PER_PARTITION,
       "period": MESSAGE_RETENTION_PERIOD,
   },
}

Go

Prima di eseguire questo esempio, segui le istruzioni per la configurazione di Go in Librerie client di Pub/Sub Lite.

import (
	"context"
	"fmt"
	"io"

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

func getTopic(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-central1"
	// 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)
	topic, err := client.Topic(ctx, topicPath)
	if err != nil {
		return fmt.Errorf("client.Topic got err: %w", err)
	}
	fmt.Fprintf(w, "Got topic: %#v\n", *topic)
	return nil
}

Java

Prima di eseguire questo esempio, segui le istruzioni di configurazione Java in Librerie client di 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.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.TopicName;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.proto.Topic;
import java.util.concurrent.ExecutionException;

public class GetTopicExample {

  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 topic.
    String topicId = "your-topic-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 = true;

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

  public static void getTopicExample(
      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)) {
      Topic topic = adminClient.getTopic(topicPath).get();
      long numPartitions = adminClient.getTopicPartitionCount(topicPath).get();
      System.out.println(topic.getAllFields() + "\nhas " + numPartitions + " partition(s).");
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This topic is not found.");
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
  }
}

Python

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Python in Librerie client di Pub/Sub Lite.

from google.api_core.exceptions import NotFound
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

location = None
if regional:
    #  A region.
    location = CloudRegion(cloud_region)
else:
    #  A zone.
    location = CloudZone(CloudRegion(cloud_region), zone_id)

topic_path = TopicPath(project_number, location, topic_id)

client = AdminClient(cloud_region)
try:
    response = client.get_topic(topic_path)
    num_partitions = client.get_topic_partition_count(topic_path)
    print(f"{response.name} has {num_partitions} partition(s).")
except NotFound:
    print(f"{topic_path} not found.")

Elenco di argomenti Lite

Puoi elencare gli argomenti Lite in un progetto utilizzando la console Google Cloud, Google Cloud CLI o l'API Pub/Sub Lite.

Console

  • Per visualizzare un elenco degli argomenti Lite in un progetto, vai alla pagina Lite Topics.

    Vai agli argomenti Lite

gcloud

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

Sostituisci LOCATION con il nome della posizione in cui si trova l'argomento Lite.

Se la richiesta ha esito positivo, la riga di comando visualizza gli argomenti Lite:

---
name: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
partitionConfig:
  count: NUMBER_OF_PARTITIONS
  capacity:
    publishMibPerSec: publish_CAPACITY
    subscribeMibPerSec: subscribe_CAPACITY
retentionConfig:
  perPartitionBytes: STORAGE_PER_PARTITION
  period: MESSAGE_RETENTION_PERIOND
---
name: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
partitionConfig:
  count: NUMBER_OF_PARTITIONS
  capacity:
    publishMibPerSec: publish_CAPACITY
    subscribeMibPerSec: subscribe_CAPACITY
retentionConfig:
  perPartitionBytes: STORAGE_PER_PARTITION
  period: MESSAGE_RETENTION_PERIOND

Protocollo

Per elencare gli argomenti Lite in un progetto, invia una richiesta GET come la seguente:

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

Sostituisci quanto segue:

  • REGION: la regione in cui si trova l'argomento Lite

  • PROJECT_NUMBER: il numero del progetto con l'argomento Lite

Se la richiesta ha esito positivo, la risposta è un elenco di argomenti Lite in formato JSON:

{
  "topics": [
      {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
      },
      {
          "name": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
      }
  ]
}

Go

Prima di eseguire questo esempio, segui le istruzioni per la configurazione di Go in Librerie client di Pub/Sub Lite.

import (
	"context"
	"fmt"
	"io"

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

func listTopics(w io.Writer, projectID, region, zone string) error {
	// projectID := "my-project-id"
	// region := "us-central1"
	// zone := "us-central1-a"
	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, zone)
	topicIter := client.Topics(ctx, parent)
	for {
		topic, err := topicIter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("topicIter.Next got err: %w", err)
		}
		fmt.Fprintf(w, "Got topic: %#v\n", topic)
	}
	return nil
}

Java

Prima di eseguire questo esempio, segui le istruzioni di configurazione Java in Librerie client di 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.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.Topic;
import java.util.List;

public class ListTopicsExample {

  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;

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

  public static void listTopicsExample(
      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<Topic> topics = adminClient.listTopics(locationPath).get();
      for (Topic topic : topics) {
        System.out.println(topic.getAllFields());
      }
      System.out.println(topics.size() + " topic(s) listed.");
    }
  }
}

Python

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Python in Librerie client di Pub/Sub Lite.

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

location = None
if regional:
    #  A region.
    location = CloudRegion(cloud_region)
else:
    #  A zone.
    location = CloudZone(CloudRegion(cloud_region), zone_id)

location_path = LocationPath(project_number, location)

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

for topic in response:
    print(topic)

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

Eliminare un argomento Lite

Puoi eliminare gli argomenti Lite con la console Google Cloud, Google Cloud CLI o l'API Pub/Sub Lite.

Console

  1. Vai alla pagina Argomenti Lite.

    Vai agli argomenti Lite

  2. Fai clic sull'ID dell'argomento Lite.

  3. Nella pagina Dettagli dell'argomento Lite, fai clic su Elimina.

  4. Nel campo visualizzato, inserisci delete per confermare che vuoi eliminare l'argomento Lite.

  5. Fai clic su Elimina.

gcloud

Per eliminare un argomento Lite, utilizza il comando gcloud pubsub lite-topics delete:

  1. Esegui il comando delete:

    gcloud pubsub lite-topics delete TOPIC_ID \
     --location=LOCATION
    

    Sostituisci quanto segue:

    • TOPIC_ID: l'ID dell'argomento Lite

    • LOCATION: il nome della posizione in cui si trova l'argomento Lite

  2. Per confermare, digita Y.

Se la richiesta ha esito positivo, la risposta è la seguente:

Deleted topic [TOPIC_ID].

Protocollo

Per eliminare un argomento Lite, invia una richiesta DELETE come la seguente:

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

Sostituisci quanto segue:

  • REGION: la regione in cui si trova l'argomento Lite

  • PROJECT_NUMBER: il numero del progetto con l'argomento Lite

  • LOCATION: il nome della posizione in cui si trova l'argomento Lite

  • TOPIC_ID: l'ID dell'argomento Lite

Se la richiesta ha esito positivo, la risposta è un oggetto JSON vuoto.

Go

Prima di eseguire questo esempio, segui le istruzioni per la configurazione di Go in Librerie client di Pub/Sub Lite.

import (
	"context"
	"fmt"
	"io"

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

func deleteTopic(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-central1"
	// 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)
	err = client.DeleteTopic(ctx, topicPath)
	if err != nil {
		return fmt.Errorf("client.DeleteTopic got err: %w", err)
	}
	fmt.Fprint(w, "Deleted topic\n")
	return nil
}

Java

Prima di eseguire questo esempio, segui le istruzioni di configurazione Java in Librerie client di 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.CloudRegionOrZone;
import com.google.cloud.pubsublite.CloudZone;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.TopicName;
import com.google.cloud.pubsublite.TopicPath;
import java.util.concurrent.ExecutionException;

public class DeleteTopicExample {

  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 topic.
    String topicId = "your-topic-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;

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

  public static void deleteTopicExample(
      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)) {
      adminClient.deleteTopic(topicPath).get();
      if (regional) {
        System.out.println(topicPath.toString() + " (regional topic) deleted successfully.");
      } else {
        System.out.println(topicPath.toString() + " (zonal topic) deleted successfully.");
      }
    } catch (ExecutionException e) {
      try {
        throw e.getCause();
      } catch (NotFoundException notFound) {
        System.out.println("This topic is not found.");
      } catch (Throwable throwable) {
        throwable.printStackTrace();
      }
    }
  }

Python

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Python in Librerie client di Pub/Sub Lite.

from google.api_core.exceptions import NotFound
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

cloud_region = CloudRegion(cloud_region)
topic_path = None
if regional:
    #  A regional topic.
    topic_path = TopicPath(project_number, cloud_region, topic_id)
else:
    #  A zonal topic
    topic_path = TopicPath(
        project_number, CloudZone(cloud_region, zone_id), topic_id
    )

client = AdminClient(cloud_region)
try:
    client.delete_topic(topic_path)
    if regional:
        print(f"{topic_path} (regional topic) deleted successfully.")
    else:
        print(f"{topic_path} (zonal topic) deleted successfully.")
except NotFound:
    print(f"{topic_path} not found.")

Se elimini un argomento Lite, non puoi pubblicare messaggi al suo interno. Le sottoscrizioni Lite per l'argomento Lite esistono ancora, ma non puoi ricevere messaggi dalle sottoscrizioni Lite.

Passaggi successivi