问题
Trying to connect to local Google PubSub emulator from Spring boot application for tests.
Using below config spring.cloud.gcp.pubsub.emulator-host=localhost:8085
Started emulator in local successfully on 8085, Also have set
PUBSUB_EMULATOR_HOST=localhost:8085
Note: While connecting to the actual Google PubSub topic everything just works fine.
回答1:
When using the Pub/Sub emulator, use the FixedTransportChannelProvider
and NoCredentialsProvider
to create a Publisher
or Subscriber
. This is demonstrated in UsePubSubEmulatorSnippet.java:
String hostport = System.getenv("PUBSUB_EMULATOR_HOST");
ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext(true).build();
TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
CredentialsProvider credentialsProvider = NoCredentialsProvider.create();
ProjectTopicName topicName = ...
// Use the channel and credentials provider when creating a Publisher or Subscriber.
Publisher publisher =
Publisher.newBuilder(topicName)
.setChannelProvider(channelProvider)
.setCredentialsProvider(credentialsProvider)
.build();
回答2:
- Create a file under
src/test/resources/application.properties
- Set
spring.cloud.gcp.pubsub.emulator-host=localhost:8085
inside the test application.properties. - Annotate your test class so that Spring picks up your test application.properties:
@RunWith(SpringRunner::class)
@SpringBootTest
EDIT: I created an example project that shows how to use Spring with PubSub emulator in a test (which also requires creating the topic and subscription): https://github.com/nhartner/pubsub-emulator-demo
来源:https://stackoverflow.com/questions/51290024/spring-boot-cloud-gcp-cannot-connect-to-local-google-pubsub-emulator