Publique e receba mensagens no Pub/Sub através de uma biblioteca de cliente

O serviço Pub/Sub permite que as aplicações troquem mensagens de forma fiável, rápida e assíncrona. Segue-se a sequência de eventos:

  1. Um produtor de dados publica uma mensagem num tópico do Pub/Sub.
  2. Um cliente subscritor cria uma subscrição para esse tópico e consome mensagens da subscrição.

Pode configurar um ambiente do Pub/Sub através de qualquer um dos seguintes métodos: Google Cloud consola, Cloud Shell, bibliotecas cliente ou APIs REST. Esta página mostra como começar a publicar mensagens com o Pub/Sub através de bibliotecas cliente.

O Pub/Sub oferece uma biblioteca de cliente gerada automaticamente de nível elevado e de nível baixo. Por predefinição, como neste início rápido, recomendamos a biblioteca de cliente de alto nível.


Para seguir orientações passo a passo para esta tarefa diretamente na Google Cloud consola, clique em Orientar-me:

Visita guiada


Antes de começar

  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. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  4. Para inicializar a CLI gcloud, execute o seguinte 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. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  12. Para inicializar a CLI gcloud, execute o seguinte 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. Instale as bibliotecas de cliente

    Os exemplos seguintes mostram como instalar as bibliotecas de cliente:

    Python

    Para mais informações sobre como configurar o ambiente de programação Python, consulte o guia de configuração do ambiente de programação Python.

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

    pip install --upgrade google-cloud-pubsub

    C++

    Para mais informações sobre a instalação da biblioteca C++, consulte o GitHub README

    C#

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

    Ir

    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

    Crie um tópico e uma subscrição

    Depois de criar um tópico, pode subscrever ou publicar nele.

    Use o seguinte comando gcloud pubsub topics create para criar um tópico com o nome my-topic. Não altere o nome do tópico, porque é referenciado ao longo do resto do tutorial.

    gcloud pubsub topics create my-topic

    Use o comando gcloud pubsub subscriptions create para criar uma subscrição. Apenas as mensagens publicadas no tópico após a criação da subscrição estão disponíveis para as aplicações subscritoras.

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

    Publique mensagens

    Antes de executar os exemplos seguintes, certifique-se de que descomenta e preenche todos os valores obrigatórios marcados no código. Isto é necessário para associar o exemplo ao seu projeto e aos recursos do Pub/Sub que criou anteriormente.

    Use my-topic para o ID do tópico.

    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::Topic(project_id, topic_id)));
      auto id =
          publisher
              .Publish(pubsub::MessageBuilder{}.SetData("Hello World!").Build())
              .get();
      if (!id) throw std::move(id).status();
      std::cout << "Hello World published with id=" << *id << "\n";
    
      return 0;
    } catch (google::cloud::Status const& status) {
      std::cerr << "google::cloud::Status thrown: " << status << "