Testing apps locally with the emulator

To develop and test your application locally, you can use the Pub/Sub emulator, which provides local emulation of the production Pub/Sub environment. You run the Pub/Sub emulator using the gcloud command-line tool.

To run your application against the emulator, you first need to start the emulator and set environment variables so that your application communicates with the emulator instead of the production Pub/Sub.

Prerequisites

You must have the following to use the Pub/Sub emulator:

Installing the emulator

Install the emulator from a command prompt:

gcloud components install pubsub-emulator
gcloud components update

Starting the emulator

Start the emulator by invoking pubsub start from a command prompt. Before running the command, replace PUBSUB_PROJECT_ID with a Google Cloud project ID. In this case, the project ID can be any valid string; it does not need to represent a real Google Cloud project because the Pub/Sub emulator runs locally.

gcloud beta emulators pubsub start --project=PUBSUB_PROJECT_ID [options]

See gcloud beta emulators pubsub start for a complete list of options.

After you start the emulator, you should see a message that resembles the following:

...
[pubsub] This is the Pub/Sub fake.
[pubsub] Implementation may be incomplete or differ from the real system.
...
[pubsub] INFO: Server started, listening on 8085

This indicates that the Pub/Sub server runs at the emulator endpoint on your local machine instead of the Google Cloud endpoint. All operations happen locally, including:

  • Creating a topic or subscription
  • Publishing
  • Subscribing

Setting environment variables

After you start the emulator, you need to set environment variables so that your application connects to the emulator instead of Pub/Sub. Set these environment variables on the same machine that you use to run your application.

You need to set the environment variables each time you start the emulator. The environment variables depend on dynamically assigned port numbers that could change when you restart the emulator.

Automatically setting the variables

If your application and the emulator run on the same machine, you can set the environment variables automatically:

Linux / macOS

Run env-init using command substitution:

$(gcloud beta emulators pubsub env-init)

Windows

Create and run a batch file using output from env-init:

gcloud beta emulators pubsub env-init > set_vars.cmd && set_vars.cmd

Your application will now connect to the Pub/Sub emulator.

Manually setting the variables

If your application and the emulator run on different machines, set the environment variables manually:

  1. Run the env-init command:

     gcloud beta emulators pubsub env-init

  2. On the machine that runs your application, set the PUBSUB_EMULATOR_HOST environment variable and value as directed by the output of the env-init command. You can optionally set the PUBSUB_PROJECT_ID environment variable for the project you want to use for the emulator, but you only need to set PUBSUB_EMULATOR_HOST for your application to connect to the emulator. For example:

    Linux / macOS
    export PUBSUB_EMULATOR_HOST=localhost:8432
    export PUBSUB_PROJECT_ID=my-project-id
    Windows
    set PUBSUB_EMULATOR_HOST=localhost:8432
    set PUBSUB_PROJECT_ID=my-project-id

Your application will now connect to the Pub/Sub emulator.

Note: If you are using the Python App Engine Standard local development server, you must pass environment variables on the command line as follows:

Python

dev_appserver.py app.yaml --env_var PUBSUB_EMULATOR_HOST=${PUBSUB_EMULATOR_HOST}

Using the emulator

To use the emulator, you must have an application built using the Google Cloud Client Libraries. The emulator does not support Cloud Console or gcloud pubsub commands.

The following example demonstrates how to create a topic, publish messages, and read messages using the emulator and an application that uses the Python Google Cloud Client Library.

Complete the following steps on the machine where you set the emulator environment variables:

  1. Get the Pub/Sub Python samples from GitHub by cloning the full Python repository. The Pub/Sub samples are in the pubsub directory.

  2. In your cloned repository, navigate to the pubsub/cloud-client directory. You'll complete the rest of these steps in this directory.

  3. From within the pubsub/cloud-client directory, install the dependencies needed to run the example:

    pip install -r requirements.txt
    
  4. Create a topic:

     python publisher.py PUBSUB_PROJECT_ID create TOPIC_ID
    
  5. (Optional) If you do not have a local push endpoint for testing push subscriptions in the emulator, complete the following steps to create one onhttp://localhost:3000/messages.

    1. Install JSON Server.
      npm install -g json-server
      
    2. Start JSON Server.
      json-server --port 3000 --watch db.json
      
      where db.json contains the following starter code:
      {
         "messages": []
      }
      
    3. Note down http://localhost:3000/messages for PUSH_ENDPOINT in the next step.
  6. Create a subscription to the topic:

    • Create a pull subscription:

      python subscriber.py PUBSUB_PROJECT_ID create TOPIC_ID SUBSCRIPTION_ID
      
    • Create a push subscription:

      python subscriber.py PUBSUB_PROJECT_ID create-push TOPIC_ID SUBSCRIPTION_ID \
      PUSH_ENDPOINT
      
  7. Publish messages to the topic:

     python publisher.py PUBSUB_PROJECT_ID publish TOPIC_ID
    
  8. Read the messages published to the topic:

    • Retrieve messages from your pull subscription:

      python subscriber.py PUBSUB_PROJECT_ID receive SUBSCRIPTION_ID
      
    • Observe the messages delivered to your local push endpoint. For example, messages look like the following:

      {
        "messages": [
            {
                "subscription": "projects/PUBSUB_PROJECT_ID/subscriptions/SUBSCRIPTION_ID",
                "message": {
                    "data": "TWVzc2FnZSBudW1iZXIgMQ==",
                    "messageId": "10",
                    "attributes": {}
                },
                "id": 1
            },
            ...
        ]
      }
      

Accessing environment variables

In all languages except for Java and C#, if you have set PUBSUB_EMULATOR_HOST as described in Setting environment variables, the Pub/Sub client libraries automatically call the API running in the local instance rather than Pub/Sub.

However, C# and Java client libraries require you to modify your code to use the emulator:

C#

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

// For example, "localhost:8615"
string emulatorHostAndPort = Environment.GetEnvironmentVariable("PUBSUB_EMULATOR_HOST");

Channel channel = new Channel(emulatorHostAndPort, ChannelCredentials.Insecure);
PublisherServiceApiClient client = PublisherServiceApiClient.Create(channel);
client.CreateTopic(new TopicName("project", "topic"));
foreach (var topic in client.ListTopics(new ProjectName("project")))
{
    Console.WriteLine(topic.Name);
}

Java

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

String hostport = System.getenv("PUBSUB_EMULATOR_HOST");
ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build();
try {
  TransportChannelProvider channelProvider =
      FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
  CredentialsProvider credentialsProvider = NoCredentialsProvider.create();

  // Set the channel and credentials provider when creating a `TopicAdminClient`.
  // Similarly for SubscriptionAdminClient
  TopicAdminClient topicClient =
      TopicAdminClient.create(
          TopicAdminSettings.newBuilder()
              .setTransportChannelProvider(channelProvider)
              .setCredentialsProvider(credentialsProvider)
              .build());

  ProjectTopicName topicName = ProjectTopicName.of("my-project-id", "my-topic-id");
  // Set the channel and credentials provider when creating a `Publisher`.
  // Similarly for Subscriber
  Publisher publisher =
      Publisher.newBuilder(topicName)
          .setChannelProvider(channelProvider)
          .setCredentialsProvider(credentialsProvider)
          .build();
} finally {
  channel.shutdown();
}

Stopping the emulator

To stop the emulator, press Control+C.

After you stop the emulator, run the following command to remove the PUBSUB_EMULATOR_HOST environment variable so your application will connect to Pub/Sub:

Linux / macOS
unset PUBSUB_EMULATOR_HOST
Windows
set PUBSUB_EMULATOR_HOST=

Emulator command-line arguments

For details on command-line arguments for the Pub/Sub emulator, see gcloud beta emulators pubsub.

Known limitations

  • UpdateTopic and UpdateSnapshot RPCs are not currently supported.
  • IAM operations are not currently supported.
  • Configurable message retention is not supported; all messages are retained indefinitely.
  • Subscription expiration is not supported. Subscriptions do not expire.

To file issues, visit the Pub/Sub forum.

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...

Cloud Pub/Sub Documentation