This code sample demonstrates how to use the Spring Cloud Stream binder for Google Cloud Pub/Sub.
The sample consists of two applications, a source (spring-cloud-gcp-pubsub-stream-functional-sample-source) and a sink (spring-cloud-gcp-pubsub-stream-functional-sample-sink). The source collects a user name and a message through a web form, adds the data along with the time of message creation to a UserMessage object, and sends it through Google Cloud Pub/Sub. The sink application simply logs the message.
If the topic for the sink and source does not exist, the binder will automatically create them in Google Cloud Pub/Sub based on the values in source and sink application.properties.
If you would like to implement load balancing with multiple subscribers reading from the same subscription, you can specify a custom group in the sink’s application.properties. If the group is not specified, an anonymous subscription with the name anonymous.<topicName>.<randomUUID> will be generated.
-
Configure your credentials and project ID by following these instructions.
Alternatively, if you have the Google Cloud SDK installed and initialized, and are logged in with application default credentials, Spring will auto-discover those parameters for you.
-
Set your project ID using the
spring.cloud.gcp.project-idproperty in application.properties or use thegcloud config set project [PROJECT_ID]Cloud SDK command. -
Run
$ mvn clean installfrom the root directory of the project.
In the application.properties file, a topic and group name are already preconfigured for you (it’s my-topic and my-group, so the subscription name used by the Sink is my-topic.my-group).
The topic and subscription will be created in your account if they do not already exist.
-
In separate terminal windows, start the
spring-cloud-gcp-pubsub-stream-functional-sample-sourceandspring-cloud-gcp-pubsub-stream-functional-sample-sinkapplications with the$ mvn spring-boot:runcommand in the same folder as the apps'pom.xmlfiles. -
Browse to the source application at
http://localhost:8080or use theWeb Previewfeature in Cloud Shell to preview the app on port 8080, type in a message and a user name, and press thePost it!button. -
Verify in the
spring-cloud-gcp-pubsub-stream-functional-sample-sinkapp’s logs that the message was received:New message received from [USERNAME] at [TIME_MESSAGE_SENT]: [MESSAGE]
Delete the test topic (my-topic) and subscription (my-topic.my-group).
Note that if you do not use the group property for the binding, the automatically created anonymous subscription (anonymous.my-topic.<randomUUID>) gets cleaned up automatically when the spring-cloud-gcp-pubsub-stream-functional-sample-sink application shuts down.