Reputation: 1230
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.
Upvotes: 1
Views: 4983
Reputation: 916
We can use Testcontainers approach for using all the supported services. It provides you with a docker container where the emulators would be running and help to use different configurations for multiple projects and update test setup as per the individual test case. For pubsub, please use the below configuration you can create the initial setup: i.e. topics and subscriptions
companion object {
private val log = logger(GCPSetup::class.java)
private val emulator: PubSubEmulatorContainer = PubSubEmulatorContainer(
DockerImageName.parse("gcr.io/google.com/cloudsdktool/cloud-sdk:316.0.0-emulators")
)
init {
emulator.start()
}
@Configuration
class EmulatorConfiguration{
@Bean
fun credentialProvider() = NoCredentialsProvider()
}
@DynamicPropertySource
fun emulatorProperties(registry:DynamicPropertyRegistry){
registry.add("spring.cloud.gcp.pubsub.emulator-host") { emulator.emulatorEndpoint }
}
}
The above example is in Kotlin, but you can use the above configuration in static block in java.
Upvotes: 0
Reputation: 2386
src/test/resources/application.properties
spring.cloud.gcp.pubsub.emulator-host=localhost:8085
inside the 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
Upvotes: 2
Reputation: 136
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();
Upvotes: 1