Publicar y recibir mensajes en Pub/Sub con una biblioteca de cliente

El servicio Pub/Sub permite que las aplicaciones intercambien mensajes de forma fiable, rápida y asíncrona. Esta es la secuencia de eventos:

  1. Un productor de datos publica un mensaje en un tema de Pub/Sub.
  2. Un cliente suscriptor crea una suscripción a ese tema y consume mensajes de la suscripción.

Puedes configurar un entorno de Pub/Sub con cualquiera de los siguientes métodos: Google Cloud consola, Cloud Shell, bibliotecas de cliente o APIs REST. En esta página se explica cómo empezar a publicar mensajes con Pub/Sub mediante bibliotecas de cliente.

Pub/Sub ofrece una biblioteca de cliente de alto nivel y otra de bajo nivel generadas automáticamente. De forma predeterminada, como en esta guía de inicio rápido, te recomendamos la biblioteca de cliente de alto nivel.


Para seguir las instrucciones paso a paso de esta tarea directamente en la Google Cloud consola, haz clic en Ayúdame:

Guíame


Antes de empezar

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  4. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  5. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Pub/Sub API:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable pubsub.googleapis.com
  8. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  9. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/pubsub.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: Your project ID.
    • USER_IDENTIFIER: The identifier for your user account. For example, myemail@example.com.
    • ROLE: The IAM role that you grant to your user account.
  10. Install the Google Cloud CLI.

  11. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  12. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  13. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  14. Verify that billing is enabled for your Google Cloud project.

  15. Enable the Pub/Sub API:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable pubsub.googleapis.com
  16. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  17. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/pubsub.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: Your project ID.
    • USER_IDENTIFIER: The identifier for your user account. For example, myemail@example.com.
    • ROLE: The IAM role that you grant to your user account.
  18. Instalar las bibliotecas de cliente

    En los siguientes ejemplos se muestra cómo instalar las bibliotecas de cliente:

    Python

    Para obtener más información sobre la configuración de tu entorno de desarrollo de Python, consulta la guía de configuración del entorno de desarrollo de Python.

    # ensure that you are using virtualenv
    # as described in the python dev setup guide

    pip install --upgrade google-cloud-pubsub

    C++

    Para obtener más información sobre cómo instalar la biblioteca de C++, consulta GitHub README.

    C#

    Install-Package Google.Cloud.PubSub.V1 -Pre

    Go

    go get cloud.google.com/go/pubsub

    Java

    If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.72.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-pubsub</artifactId>
      </dependency>
    
    </dependencies>
    

    If you are using Gradle, add the following to your dependencies:

    implementation platform('com.google.cloud:libraries-bom:26.72.0')
    
    implementation 'com.google.cloud:google-cloud-pubsub'

    If you are using sbt, add the following to your dependencies:

    libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "1.144.1"

    If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:

    The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

    Node.js

    npm install @google-cloud/pubsub

    PHP

    composer require google/cloud-pubsub

    Ruby

    gem install google-cloud-pubsub

    Crear un tema y una suscripción

    Después de crear un tema, puedes suscribirte a él o publicar contenido en él.

    Usa el siguiente comando gcloud pubsub topics create para crear un tema llamado my-topic. No cambies el nombre del tema, ya que se hace referencia a él en el resto del tutorial.

    gcloud pubsub topics create my-topic

    Usa el comando gcloud pubsub subscriptions create para crear una suscripción. Las aplicaciones suscriptoras solo pueden acceder a los mensajes publicados en el tema después de crear la suscripción.

    gcloud pubsub subscriptions create my-sub --topic my-topic

    Publica mensajes

    Antes de ejecutar los siguientes ejemplos, asegúrate de quitar los comentarios y rellenar los valores obligatorios que estén marcados en el código. Es necesario para vincular el ejemplo a tu proyecto y a los recursos de Pub/Sub que hayas creado anteriormente.

    Usa my-topic como ID de tema.

    Python

    from google.cloud import pubsub_v1
    
    # TODO(developer)
    # project_id = "your-project-id"
    # topic_id = "your-topic-id"
    
    publisher = pubsub_v1.PublisherClient()
    # The `topic_path` method creates a fully qualified identifier
    # in the form `projects/{project_id}/topics/{topic_id}`
    topic_path = publisher.topic_path(project_id, topic_id)
    
    for n in range(1, 10):
        data_str = f"Message number {n}"
        # Data must be a bytestring
        data = data_str.encode("utf-8")
        # When you publish a message, the client returns a future.
        future = publisher.publish(topic_path, data)
        print(future.result())
    
    print(f"Published messages to {topic_path}.")

    C++

    #include "google/cloud/pubsub/publisher.h"
    #include <iostream>
    
    int main(int argc, char* argv[]) try {
      if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " <project-id> <topic-id>\n";
        return 1;
      }
    
      std::string const project_id = argv[1];
      std::string const topic_id = argv[2];
    
      // Create a namespace alias to make the code easier to read.
      namespace pubsub = ::google::cloud::pubsub;
    
      auto publisher = pubsub::Publisher(
          pubsub::MakePublisherConnection(pubsub::