Creare e gestire argomenti Lite

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

Panoramica di un argomento Lite

Un servizio Pub/Sub Lite richiede un argomento a cui i publisher possono inviare in modo che i sottoscrittori possano riceverli. Entro Pub/Sub Lite, puoi scegliere di creare un'istanza Lite a livello di zona o di regione per ogni argomento.

Un argomento Lite a livello di zona e un argomento Lite a livello di regione si differenziano solo per il modo in cui vengono replicati e i dati di Google Cloud. 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 una singola regione. Replica degli argomenti di zona Pub/Sub Lite all'interno di una sola zona. Pub/Sub Lite replica i dati in modo asincrono.

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

La disponibilità di un argomento a livello di zona di Pub/Sub Lite dipende la disponibilità sia del frontend dell'applicazione sia dell'archiviazione zona di destinazione. 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 non sarà disponibile per la durata dell'interruzione.

La disponibilità di un argomento regionale di Pub/Sub Lite dipende dal la disponibilità del frontend e dell'archiviazione dell'applicazione nella regione configurata. Sono possibili i seguenti tipi di errore:

  • Se si verifica un errore a livello di zona per l'archiviazione frontend o dell'applicazione, l'argomento Lite a livello di regione rimangono disponibili.

  • Se si verifica un errore a livello di zona sia per il frontend dell'applicazione sia per lo spazio di archiviazione l'argomento Lite a livello di regione rimane disponibile purché l'errore di entrambi i componenti non inizi contemporaneamente nel tempo.

  • Se il frontend e l'archiviazione dell'applicazione hanno esito negativo contemporaneamente, l'argomento Lite a livello di regione rimane non disponibile per la durata dell'interruzione. Durante questo periodo, i client potrebbero non pubblicare o utilizzare messaggi, ma i messaggi restano consegnato nell'ordine corretto.

Un argomento Lite a livello di regione offre protezione dalla maggior parte dei tipi di zone singole errori. Tuttavia, in alcuni rari casi, la natura asincrona della replica può causano il guasto simultaneo di più componenti in una singola zona. Come un argomento Lite a livello di regione diventa non 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 le tre proprietà seguenti:

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

    • Velocità effettiva di sottoscrizione (MiBps). La tariffa massima in cui i messaggi vengono inoltrati alle sottoscrizioni Lite.

    • Spazio di archiviazione (GiB). La dimensione massima dei messaggi nella partizione. La capacità minima configurabile di una partizione è di 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 dispositivo Lite indica la somma della capacità di archiviazione di tutte le partizioni dell'argomento. Per Ad esempio, se un argomento Lite ha 8 partizioni e ogni partizione ha una dimensione 30 GiB, la capacità di archiviazione totale dell'argomento Lite è di 240 GiB (8 x 30).

  • Capacità di velocità effettiva di un argomento Lite. La capacità di velocità effettiva è composta capacità di velocità effettiva totale di pubblicazione e sottoscrizione di tutte le partizioni in 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 limita in modo efficace la velocità effettiva.

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

  • Prenotazioni. Una prenotazione è il modo più semplice per eseguire il provisioning per una serie di argomenti. Capacità di velocità effettiva di provisioning con prenotazioni è obbligatorio per le versioni Lite a livello di regione ed è facoltativo per le applicazioni Argomenti Lite.

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

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

    • Periodo di conservazione dei messaggi. Il periodo di tempo massimo per cui un elemento Lite per archiviare 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à di archiviazione. La capacità dell'argomento Pub/Sub Lite è determinato 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. Tieni presente che gli argomenti Lite a livello di regione utilizzano due byte di spazio di archiviazione per ogni byte pubblicato. Gli argomenti Lite a livello di zona utilizzano un byte di spazio di archiviazione per ogni byte pubblicato.

    Se superi la capacità di archiviazione, il servizio Pub/Sub Lite continua a pubblicare messaggi. Tuttavia, per creare altro spazio di archiviazione di capacità elevata, vengono eliminati i messaggi più vecchi della partizione. L'eliminazione di i messaggi più vecchi si verificano anche se si trovano all'interno del messaggio periodo di conservazione. Il servizio non elimina mai i messaggi prima del relativo TTL scadono, a meno che la loro rimozione non sia necessaria per fare spazio ai messaggi. Per informazioni sulla correlazione tra la capacità e i prezzi, vedi Pub/Sub Prezzi Lite.

Linee guida per assegnare un nome a un argomento

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

projects/project-identifier/collection/ID

  • project-identifier: deve essere l'ID o il numero di progetto, disponibile nel 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
    • Contenere 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 dell'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 esegui chiamate REST.

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

Se non usi 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 dai seguenti limiti:

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

  • Velocità effettiva di sottoscrizione 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 all'interno specificati, purché la capacità totale la prenotazione non sia stata superata. Facoltativamente, puoi impostare un limite inferiore per e 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 diminuito.

Quando modifichi il numero di partizioni, l'ordine relativo dei messaggi non viene vengono conservati. Internamente, i messaggi vengono assegnati alle partizioni tramite un hash personalizzata. L'aggiornamento del numero di partizioni in un argomento modifica questo hash personalizzata. Messaggi con la stessa chiave pubblicati dopo l'aggiornamento del conteggio delle partizioni verranno probabilmente mappati su una partizione diversa da quelle pubblicate prima aggiornamento.

Inoltre, la propagazione del ridimensionamento dell'argomento a tutti gli argomenti richiede alcuni secondi i publisher. C'è poco tempo in cui alcuni publisher usano il nuovo la funzione hash e alcuni usano ancora quella precedente.

Aumenta la capacità di archiviazione di un argomento Lite

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

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

Per informazioni sulla correlazione tra la capacità e i prezzi, consulta Prezzi di Pub/Sub Lite

Crea un argomento Lite

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

Per un elenco delle regioni e delle zone disponibili, vedi Località 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 al suo interno.

    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.

      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. Tu puoi modificare questo numero dopo aver salvato l'argomento.

  5. Nella sezione Archiviazione messaggi:

    1. Inserisci lo spazio di archiviazione per partizione.

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

  6. Rivedi le modifiche e fai clic su Crea.

gcloud

Per creare un argomento Lite, utilizza 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 in sull'argomento Lite

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

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

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

Se la richiesta ha esito positivo, la riga di comando visualizza una 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 in sull'argomento Lite

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

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

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

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

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

Se la richiesta ha esito positivo, la risposta è 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
  }
}

Vai

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Go in Librerie client 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 di Java in Librerie client 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 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 per partizione e capacità di archiviazione. Puoi anche aumentare, ma non diminuire il numero partizioni di Compute Engine.

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)

  • Limiti di capacità di 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 Consulta Scala la capacità di velocità effettiva e Scala l'archiviazione dei carichi di lavoro.

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 argomento Lite.

  3. Fai clic su Modifica.

  4. Puoi apportare uno o tutti i seguenti aggiornamenti:

    • Usa 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 di zona, aggiorna la velocità effettiva di pubblicazione e sottoscrizione prenotata. Per gli argomenti con una prenotazione allegata, 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 Aggiorna.

gcloud

Per aggiornare un argomento Lite, utilizza 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 località in cui si trova l'argomento Lite

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

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

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

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

  • MESSAGE_RETENTION_PERIOD: per quanto tempo l'argomento Lite archivia messaggi, come 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 la versione Lite argomento

  • LOCATION: il nome della località 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 velocità effettiva di pubblicazione di ogni partizione

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

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

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

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

Se la richiesta ha esito positivo, la risposta è 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,
   },
}

Vai

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Go in Librerie client 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 di Java in Librerie client 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 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 il 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 argomento Lite.

gcloud

Per ottenere dettagli su un argomento Lite, utilizza 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 località 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 ricevere 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 la versione Lite argomento

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

  • TOPIC_ID: l'ID dell'argomento Lite

Se la richiesta ha esito positivo, la risposta è 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,
   },
}

Vai

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Go in Librerie client 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 di Java in Librerie client 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 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 di 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 Argomenti Lite.

    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 la versione Lite argomento

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

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

Vai

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Go in Librerie client 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 di Java in Librerie client 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 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 oppure l'API Pub/Sub Lite.

Console

  1. Vai alla pagina Argomenti Lite.

    Vai agli argomenti Lite

  2. Fai clic sull'ID argomento Lite.

  3. Nella pagina Dettagli 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 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 località 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 la versione Lite argomento

  • LOCATION: il nome della località 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.

Vai

Prima di eseguire questo esempio, segui le istruzioni di configurazione di Go in Librerie client 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 di Java in Librerie client 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 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. Lite esistono ancora sottoscrizioni all'argomento Lite, ma non puoi ricevere messaggi dalle sottoscrizioni Lite.

Passaggi successivi