Pub/Sub Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Pub/Sub API.

Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Installing the client library

C++

For more information about installing the C++ library, see the GitHub README.

C#

For more information, see Setting Up a C# Development Environment.

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

Go

For more information, see Setting Up a Go Development Environment.

go get -u cloud.google.com/go/pubsub

Java

For more information, see Setting Up a Java Development Environment.

Wenn Sie Maven verwenden, fügen Sie Ihrer Datei pom.xml den folgenden Code hinzu. Weitere Informationen zu BOMs finden Sie unter The Google Cloud Platform Libraries BOM.

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

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-pubsub</artifactId>
  </dependency>

Wenn Sie Gradle verwenden, fügen Sie den Abhängigkeiten Folgendes hinzu:

compile 'com.google.cloud:google-cloud-pubsub:1.109.0'

Wenn Sie sbt nutzen, fügen Sie den Abhängigkeiten Folgendes hinzu:

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

Bei Verwendung von IntelliJ oder Eclipse können Sie Ihrem Projekt mithilfe der folgenden IDE-Plug-ins Clientbibliotheken hinzufügen:

Diese Plug-ins bieten zusätzliche Funktionen wie die Schlüsselverwaltung für Dienstkonten. Einzelheiten finden Sie in der Dokumentation der einzelnen Plug-ins.

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/pubsub

PHP

For more information, see Using PHP on Google Cloud.

composer require google/cloud-pubsub

Python

For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-pubsub

Ruby

For more information, see Setting Up a Ruby Development Environment.

gem install google-cloud-pubsub

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console

  1. Wechseln Sie in der Cloud Console zur Seite Dienstkontoschlüssel erstellen.

    Zur Seite „Dienstkontoschlüssel erstellen“
  2. Wählen Sie aus der Liste Dienstkonto die Option Neues Dienstkonto aus.
  3. Geben Sie im Feld Dienstkontoname einen Namen ein.
  4. Wählen Sie in der Liste Rolle die Option Projekt > Inhaber

  5. Klicken Sie auf Erstellen. Eine JSON-Datei mit Ihrem Schlüssel wird auf Ihren Computer heruntergeladen.

Befehlszeile

Sie können die folgenden Befehle mithilfe des Cloud SDK auf Ihrem lokalen Computer oder in Cloud Shell ausführen.

  1. Erstellen Sie das Dienstkonto. Ersetzen Sie NAME mit einem Namen für das Dienstkonto.

    gcloud iam service-accounts create NAME
  2. Gewähren Sie dem Dienstkonto Berechtigungen. Geben Sie für PROJECT_ID Ihre Projekt-ID an.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. Erstellen Sie die Schlüsseldatei. Geben Sie für FILE_NAME einen Namen für die Schlüsseldatei an.

    gcloud iam service-accounts keys create FILE_NAME.json --iam-account=NAME@PROJECT_ID.iam.gserviceaccount.com

Die Anmeldedaten zur Authentifizierung für Ihren Anwendungscode geben Sie durch Festlegung der Umgebungsvariable GOOGLE_APPLICATION_CREDENTIALS an. Geben Sie für [PATH] den Dateipfad der JSON-Datei an, die Ihren Dienstkontoschlüssel enthält. Diese Variable gilt nur für Ihre aktuelle Shell-Sitzung. Wenn Sie eine neue Sitzung öffnen, müssen Sie die Variable neu festlegen.

Linux oder macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Beispiel:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

Windows

Mit PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Beispiel:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"

Mit Eingabeaufforderung:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C++

Before trying this sample, follow the C++ setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub C++ API reference documentation.

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string project_id,
   std::string topic_id) {
  auto topic = client.CreateTopic(pubsub::TopicBuilder(
      pubsub::Topic(std::move(project_id), std::move(topic_id))));
  // Note that kAlreadyExists is a possible error when the library retries.
  if (topic.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The topic already exists\n";
    return;
  }
  if (!topic) throw std::runtime_error(topic.status().message());

  std::cout << "The topic was successfully created: " << topic->DebugString()
            << "\n";
}

C#

Before trying this sample, follow the C# setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub C# API reference documentation.


using Google.Cloud.PubSub.V1;
using Grpc.Core;
using System;

public class CreateTopicSample
{
    public Topic CreateTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        var topicName = TopicName.FromProjectTopic(projectId, topicId);
        Topic topic = null;

        try
        {
            topic = publisher.CreateTopic(topicName);
            Console.WriteLine($"Topic {topic.Name} created.");
        }
        catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            Console.WriteLine($"Topic {topicName} already exists.");
        }
        return topic;
    }
}

Go

Before trying this sample, follow the Go setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Go API reference documentation.

If you're using the first generation of the App Engine standard runtime, we recommend using the older Google APIs Client Libraries. See this GitHub issue for more details.

// Sample pubsub-quickstart creates a Google Cloud Pub/Sub topic.
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/pubsub"
)

func main() {
	ctx := context.Background()

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the id for the new topic.
	topicID := "my-topic"

	// Creates the new topic.
	topic, err := client.CreateTopic(ctx, topicID)
	if err != nil {
		log.Fatalf("Failed to create topic: %v", err)
	}

	fmt.Printf("Topic %v created.\n", topic)
}

Java

Before trying this sample, follow the Java setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Java API reference documentation.


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class CreateTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    createTopicExample(projectId, topicId);
  }

  public static void createTopicExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      Topic topic = topicAdminClient.createTopic(topicName);
      System.out.println("Created topic: " + topic.getName());
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Node.js API reference documentation.

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

async function quickstart(
  projectId = 'your-project-id', // Your Google Cloud Platform project ID
  topicName = 'my-topic', // Name for the new topic to create
  subscriptionName = 'my-sub' // Name for the new subscription to create
) {
  // Instantiates a client
  const pubsub = new PubSub({projectId});

  // Creates a new topic
  const [topic] = await pubsub.createTopic(topicName);
  console.log(`Topic ${topic.name} created.`);

  // Creates a subscription on that new topic
  const [subscription] = await topic.createSubscription(subscriptionName);

  // Receive callbacks for new messages on the subscription
  subscription.on('message', message => {
    console.log('Received message:', message.data.toString());
    process.exit(0);
  });

  // Receive callbacks for errors on the subscription
  subscription.on('error', error => {
    console.error('Received error:', error);
    process.exit(1);
  });

  // Send a message to the topic
  topic.publish(Buffer.from('Test message!'));
}

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub PHP API reference documentation.

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\PubSub\PubSubClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$pubsub = new PubSubClient([
    'projectId' => $projectId
]);

# The name for the new topic
$topicName = 'my-new-topic-2';

# Creates the new topic
$topic = $pubsub->createTopic($topicName);

echo 'Topic ' . $topic->name() . ' created.';

Python

Before trying this sample, follow the Python setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)

topic = publisher.create_topic(request={"name": topic_path})

print("Created topic: {}".format(topic.name))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Ruby API reference documentation.

# Imports the Google Cloud client library
require "google/cloud/pubsub"

# Instantiates a client
pubsub = Google::Cloud::Pubsub.new

# The name for the new topic
# topic_name = "my-new-topic"

# Creates the new topic
topic = pubsub.create_topic topic_name

puts "Topic #{topic.name} created."

Additional resources