Publier et recevoir des messages dans Pub/Sub à l'aide d'une bibliothèque cliente
Le service Pub/Sub permet aux applications d'échanger des messages de manière fiable, rapide et asynchrone. Voici la séquence des événements:
- Un producteur de données publie un message dans un sujet Pub/Sub.
- Un client abonné crée un abonnement associé à ce sujet et utilise messages de l'abonnement.
Vous pouvez configurer un environnement Pub/Sub à l'aide de l'une des méthodes suivantes : console Google Cloud, Cloud Shell, bibliothèques clientes ou API REST. Sur cette page, nous vous expliquons comment faire vos premiers pas avec Pub/Sub pour publier des messages à l'aide de bibliothèques clientes.
Pub/Sub propose des couches de sécurité de haut niveau et de bas bibliothèque cliente. Par défaut, comme dans ce guide de démarrage rapide, nous vous recommandons d'utiliser la bibliothèque cliente de haut niveau.
Pour obtenir des instructions détaillées sur cette tâche directement dans la console Google Cloud, cliquez sur Visite guidée :
Avant de commencer
- Connectez-vous à votre compte Google Cloud. Si vous débutez sur Google Cloud, créez un compte pour évaluer les performances de nos produits en conditions réelles. Les nouveaux clients bénéficient également de 300 $ de crédits gratuits pour exécuter, tester et déployer des charges de travail.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
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.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Pub/Sub API:
gcloud services enable pubsub.googleapis.com
-
Create local authentication credentials for your user account:
gcloud auth application-default login
-
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_IDENTIFIER" --role=ROLE
- Replace
PROJECT_ID
with your project ID. -
Replace
USER_IDENTIFIER
with the identifier for your user account. For example,user:myemail@example.com
. - Replace
ROLE
with each individual role.
- Replace
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
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.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Pub/Sub API:
gcloud services enable pubsub.googleapis.com
-
Create local authentication credentials for your user account:
gcloud auth application-default login
-
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_IDENTIFIER" --role=ROLE
- Replace
PROJECT_ID
with your project ID. -
Replace
USER_IDENTIFIER
with the identifier for your user account. For example,user:myemail@example.com
. - Replace
ROLE
with each individual role.
- Replace
Installer les bibliothèques clientes
Les exemples suivants vous montrent comment installer les bibliothèques clientes :
Python
Pour en savoir plus sur la configuration de votre environnement de développement Python, consultez le guide de configuration d'un environnement de développement Python.
# ensure that you are using virtualenv
# as described in the python dev setup guide
pip install --upgrade google-cloud-pubsub
C++
Pour en savoir plus sur l'installation de la bibliothèque C++, consultez la page 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.
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, IntelliJ, or Eclipse, 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 --save @google-cloud/pubsub
PHP
composer require google/cloud-pubsub
Ruby
gem install google-cloud-pubsub
Créer un sujet et un abonnement
Après avoir créé un sujet, vous pouvez vous y abonner ou y publier des messages.
Utilisez les éléments suivants :
gcloud pubsub topics
create pour créer un sujet nommé my-topic
. Ne pas modifier
le nom du sujet, car il est référencé dans le reste du
tutoriel.
gcloud pubsub topics create my-topic
Exécutez la commande gcloud pubsub subscriptions create pour créer un abonnement. Seuls les messages publiés dans le sujet après la création de l'abonnement sont disponibles pour les applications d'abonnés.
gcloud pubsub subscriptions create my-sub --topic my-topic
Pour en savoir plus sur l'attribution de nom à vos sujets et à vos abonnements, consultez la section Noms de ressources.
Publier des messages
Avant d'exécuter les exemples suivants, assurez-vous de décommenter et de renseigner toutes les valeurs requises marquées dans le code. Cette étape est obligatoire pour associer à votre projet et aux ressources Pub/Sub que vous avez créées plus tôt.
Utilisez my-topic
pour l'ID de votre sujet.
Python
C++
C#
Go
Java
Node.js
Node.js
PHP
Ruby
Recevoir des messages
Configurez un abonné pour extraire les messages que vous venez de publier. Les abonnés doivent accuser réception de chaque message pendant une période configurable. Les messages non confirmés seront à nouveau distribués. Notez que Pub/Sub distribue parfois un message plusieurs fois pour garantir que tous les messages parviennent à un abonné au moins une fois.
Avant d'exécuter les exemples suivants, veillez à annuler la mise en commentaire et à renseigner les valeurs obligatoires indiquées dans le code. Cette étape est obligatoire pour associer à votre projet et aux ressources Pub/Sub que vous avez créées plus tôt
Utilisez my-sub
comme ID d'abonnement.
Pour obtenir d'autres exemples illustrant comment extraire des messages, consultez la section Exemples de code de la bibliothèque cliente.
Python
C++
C#
Go
Java
Node.js
PHP
Ruby
Comment ça s'est passé ?
Effectuer un nettoyage (facultatif)
- Afin d'éviter que des frais ne soient facturés sur votre compte Google Cloud pour
utilisées dans ce guide, vous pouvez utiliser la ligne de commande
pour supprimer le sujet et l'abonnement.
gcloud pubsub subscriptions delete my-sub gcloud pubsub topics delete my-topic
-
Optional: Revoke the authentication credentials that you created, and delete the local credential file.
gcloud auth application-default revoke
-
Optional: Revoke credentials from the gcloud CLI.
gcloud auth revoke
Étape suivante
En savoir plus sur les concepts Pub/Sub abordés sur cette page.
Découvrez les principes de base du service Pub/Sub.
Découvrez comment créer un système Pub/Sub de type un à plusieurs pour créer une application d'éditeur qui publie du contenu dans deux applications d'abonné distinctes.
Suivez un autre guide de démarrage rapide de Pub/Sub utilise la gcloud CLI ; ou la console.
Choisissez ou créez un abonnement.
En savoir plus sur les API Pub/Sub.
Découvrez comment exécuter Pub/Sub à l'aide de Kotlin.