Use emulator

Configures your code to use the emulator instead of the real Pub/Sub service. Applies to C# and Java.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

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.

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

PublisherServiceApiClient client = new PublisherServiceApiClientBuilder
{
    Endpoint = emulatorHostAndPort,
    ChannelCredentials = ChannelCredentials.Insecure
}.Build();
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 Pub/Sub Quickstart Using Client Libraries. For more information, see the 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());

  TopicName topicName = TopicName.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();
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser