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:
- Um produtor de dados publica uma mensagem num tópico do Pub/Sub.
- 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:
Antes de começar
- 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.
-
Install the Google Cloud CLI.
-
Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.
-
Para inicializar a CLI gcloud, execute o seguinte comando:
gcloud init -
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_IDwith 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_IDwith your Google Cloud project name.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enablepermission. Learn how to grant roles.gcloud services enable pubsub.googleapis.com
-
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.
-
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/pubsub.admingcloud 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.
-
Install the Google Cloud CLI.
-
Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.
-
Para inicializar a CLI gcloud, execute o seguinte comando:
gcloud init -
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_IDwith 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_IDwith your Google Cloud project name.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enablepermission. Learn how to grant roles.gcloud services enable pubsub.googleapis.com
-
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.
-
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/pubsub.admingcloud 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.
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.
If you are using Gradle, add the following to your dependencies:
If you are using sbt, add the following to your dependencies:
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
C++
C#