Quickstart: Using Client Libraries | Cloud Pub/Sub Documentation


The Pub/Sub service allows applications to exchange messages reliably, quickly, and asynchronously. To accomplish this, a producer of data publishes a messages to a Pub/Sub topic. A subscriber client then creates a subscription to that topic and consumes messages from the subscription. Pub/Sub persists messages that could not be delivered reliably for up to seven days. This page shows you how to get started publishing messages with Pub/Sub using client libraries.

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Set up a Cloud Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Pub/Sub API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the Cloud Console.

  3. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

  4. Install and initialize the Cloud SDK.

If you are using the SDK (rather than the Cloud Shell), install the client libraries in your programming language of choice:

Once you create a topic, you can subscribe or publish to it.

Use the gcloud pubsub topics create command to create a topic:

gcloud pubsub topics create my-topic

Use the gcloud pubsub subscriptions create command to create a subscription. Only messages published to the topic after the subscription is created are available to subscriber applications.

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

For more information about naming your topics and subscriptions, see Resource names.

Publishing messages

Receiving messages

Set up a subscriber to pull the messages you just published. Every subscriber must acknowledge each message within a configurable time window. Unacknowledged messages are redelivered. Note that Pub/Sub occasionally delivers a message more than once to ensure that all messages make it to a subscriber at least once. Here is an example of how you might receive and acknowledge messages:

import ( "context" "fmt" "io" "sync" "cloud.google.com/go/pubsub"
) func pullMsgs(w io.Writer, projectID, subID string, topic *pubsub.Topic) error { // projectID := "my-project-id" // subID := "my-sub" // topic of type https://godoc.org/cloud.google.com/go/pubsub#Topic ctx := context.Background() client, err := pubsub.NewClient(ctx, projectID) if err != nil { return fmt.Errorf("pubsub.NewClient: %v", err) } // Publish 10 messages on the topic. var results []*pubsub.PublishResult for i := 0; i < 10; i++ { res := topic.Publish(ctx, &pubsub.Message{ Data: []byte(fmt.Sprintf("hello world #%d", i)), }) results = append(results, res) } // Check that all messages were published. for _, r := range results { _, err := r.Get(ctx) if err != nil { return fmt.Errorf("Get: %v", err) } } // Consume 10 messages. var mu sync.Mutex received := 0 sub := client.Subscription(subID) cctx, cancel := context.WithCancel(ctx) err = sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) { fmt.Fprintf(w, "Got message: %q\n", string(msg.Data)) msg.Ack() mu.Lock() defer mu.Unlock() received++ if received == 10 { cancel() } }) if err != nil { return fmt.Errorf("Receive: %v", err) } return nil
}

How did it go?

Clean up (optional)

To avoid incurring charges to your Google Cloud Platform account for the resources used in this guide, you can use the command line to delete the topic and subscription.

 gcloud pubsub subscriptions delete my-sub gcloud pubsub topics delete my-topic