Calling Google Cloud Services in Java
source link: http://www.java-allandsundry.com/2022/04/calling-google-cloud-services-injava.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Calling Google Cloud Services in Java
If you want to call Google Cloud Services using a Java based codebase, then broadly there are two approaches to incorporating the client libraries in your code — the first, let’s call it a “direct” approach is to use the Google Cloud Client libraries available here, the second approach is to use a “wrapper”, Spring Cloud GCP libraries available here.
So given both these libraries which one should you use. My take is simple — if you have a Spring Boot based app likely Spring Cloud GCP should be the preferred approach else the “direct” libraries.
Using Pub/Sub Client libraries
Direct Approach
implementation platform( 'com.google.cloud:libraries-bom:25.1.0' ) implementation( 'com.google.cloud:google-cloud-pubsub' ) |
With the library pulled in, the code to publish a message looks like this:
Publisher publisher = Publisher.newBuilder( "sampletopic" ).build(); |
Spring Cloud GCP Approach
dependencies { implementation 'com.google.cloud:spring-cloud-gcp-starter-pubsub' } dependencyManagement { imports { mavenBom "com.google.cloud:spring-cloud-gcp-dependencies:${springCloudGcpVersion}" mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } |
Comparison
- Spring Cloud GCP has taken care of a bunch of boiler plate around how to create a Publisher (and subscriber if listening to messages)
- The PubSubTemplate provides simpler helper methods for publishing messages and for listening to messages, the return type which is ListenableFuture with PubSubTemplate can easily be transformed to reactive types unlike the ApiFuture return type
- Testing with Spring Cloud GCP is much simpler as the Publisher needs to be tweaked extensively to work with an emulator and Spring Cloud GCP handles this complication under the covers
Conclusion
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK