Cloud Pub/Sub Client Libraries

This page shows how to get started with the new Cloud Client Libraries for the Google Cloud Pub/Sub API. However, we recommend using the older Google APIs Client Libraries if running on Google App Engine standard environment. Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Installing the client library

C#

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

Go

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

Java

If you are using Maven, add this to your pom.xml file:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-pubsub</artifactId>
  <version>0.24.0-beta</version>
</dependency>
If you are using Gradle, add this to your dependencies:
compile 'com.google.cloud:google-cloud-pubsub:0.24.0-beta'
If you are using SBT, add this to your dependences:
libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "0.24.0-beta"

Node.js

npm install --save @google-cloud/pubsub

PHP

composer require google/cloud-pubsub

Python

pip install --upgrade google-cloud-pubsub

Ruby

gem install google-cloud-pubsub

Using the client library

The following example shows how to use the client library.

To run it on your local workstation you must first install the Google Cloud SDK and authenticate by running the following command:

gcloud auth application-default login

For information about authenticating in other environments, see setting up authentication for server to server production applications.

C#

using Google.Cloud.PubSub.V1;
using System;
using System.Diagnostics;

namespace GoogleCloudSamples
{
    class QuickStart
    {
        static void Main(string[] args)
        {
            // Instantiates a client
            PublisherClient publisher = PublisherClient.Create();

            // Your Google Cloud Platform project ID
            string projectId = "YOUR-PROJECT-ID";

            // The name for the new topic
            var topicName = new TopicName(projectId, "my-new-topic");

            // Creates the new topic
            try
            {
                Topic topic = publisher.CreateTopic(topicName);
                Console.WriteLine($"Topic {topic.Name} created.");
            }
            catch (Grpc.Core.RpcException e)
            when (e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
            {
                Console.WriteLine($"Topic {topicName} already exists.");
            }
        }
    }
}
Read more in the C# API Reference Documentation for the Google Cloud Pub/Sub Client Library.

Go

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

import (
	"fmt"
	"log"

	// Imports the Google Cloud Pub/Sub client package.
	"cloud.google.com/go/pubsub"
	"golang.org/x/net/context"
)

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 name for the new topic.
	topicName := "my-new-topic"

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

	fmt.Printf("Topic %v created.\n", topic)
}
Read more in the Go API Reference Documentation for the Google Cloud Pub/Sub Client Library.

Java

// Imports the Google Cloud client library
import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.TopicName;

public class CreateTopicExample {

  /**
   * Create a topic.
   *
   * @param args topicId
   * @throws Exception exception thrown if operation is unsuccessful
   */
  public static void main(String... args) throws Exception {

    // Your Google Cloud Platform project ID
    String projectId = ServiceOptions.getDefaultProjectId();

    // Your topic ID, eg. "my-topic"
    String topicId = args[0];

    // Create a new topic
    TopicName topic = TopicName.create(projectId, topicId);
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      topicAdminClient.createTopic(topic);
    }

    System.out.printf("Topic %s:%s created.\n", topic.getProject(), topic.getTopic());
  }
}
Read more in the Java API Reference Documentation for the Google Cloud Pub/Sub Client Library.

Node.js

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

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const pubsubClient = PubSub({
  projectId: projectId
});

// The name for the new topic
const topicName = 'my-new-topic';

// Creates the new topic
pubsubClient.createTopic(topicName)
  .then((results) => {
    const topic = results[0];
    console.log(`Topic ${topic.name} created.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });
Read more in the Node.js API Reference Documentation for the Google Cloud Pub/Sub Client Library.

PHP

# 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';

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

echo 'Topic ' . $topic->name() . ' created.';
Read more in the PHP API Reference Documentation for the Google Cloud Pub/Sub Client Library.

Python

# Imports the Google Cloud client library
from google.cloud import pubsub_v1

# Instantiates a client
publisher = pubsub_v1.PublisherClient()

# The resource path for the new topic contains the project ID
# and the topic name.
topic_path = publisher.topic_path(
    'my-project', 'my-new-topic')

# Create the topic.
topic = publisher.create_topic(topic_path)

print('Topic created: {}'.format(topic))
Read more in the Python API Reference Documentation for the Google Cloud Pub/Sub Client Library.

Ruby

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

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

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

# 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."
Read more in the Ruby API Reference Documentation for the Google Cloud Pub/Sub Client Library.

Additional Resources

外出先でもリソースをモニタリング

Google Cloud Console アプリを入手して、プロジェクトの管理にお役立てください。

フィードバックを送信...