In this series of labs, you take a demo microservices Java application built with the Spring framework and modify it to use an external database server. You adopt some of the best practices for tracing, configuration management, and integration with other services using integration patterns.
In a previous lab, you modified the application to use Cloud SQL for database services. Cloud SQL provides a managed database service for applications that require robust relational database services. But when higher performance and transactions are critical to your application, you can use Spanner to provide high-performance, relational database services. Spanner is an enterprise-grade, globally distributed, strongly consistent database service built for the cloud specifically to combine the benefits of relational database structure with non-relational horizontal scale. This combination delivers high-performance transactions and strong consistency across rows, regions, and continents with enterprise-grade security.
In this lab, you update your application to integrate your Spanner instance with Spring Data. You will then test the changes locally in Cloud Shell, and then redeploy the backend service to App Engine.
Objectives
In this lab, you learn how to perform the following tasks:
Create a Spanner instance and database
Use the data definition language (DDL) to create a Spanner table
Use Spring to add support for Spanner to an application
Modify a Java application to use Spanner instead of Cloud SQL
Setup and requirements
How to start your lab and sign in to the Console
Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method.
On the left is a panel populated with the temporary credentials that you must use for this lab.
Copy the username, and then click Open Google Console.
The lab spins up resources, and then opens another tab that shows the Choose an account page.
Note: Open the tabs in separate windows, side-by-side.
On the Choose an account page, click Use Another Account. The Sign in page opens.
Paste the username that you copied from the Connection Details panel. Then copy and paste the password.
Note: You must use the credentials from the Connection Details panel. Do not use your Google Cloud Skills Boost credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges).
Click through the subsequent pages:
Accept the terms and conditions.
Do not add recovery options or two-factor authentication (because this is a temporary account).
Do not sign up for free trials.
After a few moments, the Cloud console opens in this tab.
Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left.
After you complete the initial sign-in steps, the project dashboard appears.
Task 1. Fetch the application source files
In this task, you clone the source repository files that are used throughout this lab.
To begin the lab, click the Activate Cloud Shell button at the top of the Google Cloud Console.
To activate the code editor, click the Open Editor button on the toolbar of the Cloud Shell window.
You can switch between Cloud Shell and the code editor by using Open Editor and Open Terminal icon as required.
Note: A Cloud Storage bucket that is named using the project ID for this lab is automatically created for you by the lab setup. The source code for your applications is copied into this bucket once the Cloud SQL server is ready and both application microservices components have been deployed to App Engine. You might have to wait up to 10 minutes for the deployment tasks to complete.
In Cloud Shell, enter the following command to create an environment variable that contains the project ID for this lab:
export PROJECT_ID=$(gcloud config list --format 'value(core.project)')
Verify that the demo application files were created:
Check that the frontend application is running. You can find the URL of the frontend application that should now be running on App Engine by using the following command:
gcloud app browse
Click the link to open a browser tab to the frontend URL. You will come back to this later.
Task 2. Enable Spanner API
In this task, you enable Spanner API so that you can create a Spanner database for your application.
Switch back to Cloud Shell and enable the Spanner API:
gcloud services enable spanner.googleapis.com
Task 3. Create a new Spanner instance
In this task, you create a Spanner instance, a database, and a database table.
Create a Spanner instance
You create a Spanner instance, and then create a database on that instance for the demo application.
On the Google Cloud console title bar, in the Search field, type Spanner , click Search, and then click Spanner.
Click the name of the Guestbook messages instance to open it.
Click the name of the messages database to open it.
You should see the guestbook_message table only after the spanner.ddl file was processed successfully.
Click the guestbook_message table to open it.
The database opens showing the schema details tab. You can click the Show Equivalent DDL button, the schema should match the schema you created in the spanner.ddl file. Click Close.
Click the Data tab. There is no data in the table yet.
Task 4. Add Spanner Starter for Spring Cloud
In this task, you update the Guestbook Service's pom.xml file to remove the Cloud SQL starter, and add the Spanner starter dependency.
Switch back to the tab running the Cloud Shell code editor.
In the editor, open ~/guestbook-service/pom.xml.
Delete the Spring Data JPA by removing these lines:
In this task, you add the Spanner instance and database configuration properties to application.properties and application-cloud.properties for the guestbook backend service application. You will also delete the Cloud SQL configuration properties.
There is no Spanner emulator, meaning both Dev and Prod will always need a real Spanner instance running. For this lab, we'll use the same Spanner instance.
In the editor, open ~/guestbook-service/src/main/resources/application.properties. Delete the two Cloud SQL Configuration lines and add the following Spanner configuration:
In this task, you modify GuestbookMessage.java to use the Spanner annotations.
You can use the @Table annotation to map a Java class to a Spanner table. And you can use the @Column annotation to map properties to table columns. You use the @Table annotation to map to the guestbook_message table that was created when you ran the DDL statement with gcloud CLI.
The ID property is specified as the primary key. In the class constructor, the ID property is auto-populated with a random UUID. The UUIDv4 format is recommended over a monotonically increasing ID. This format helps Spanner avoid creating hotspots when it automatically shards the data.
The other class properties included match the table's schema in the DDL statement, except for imageUri, which uses the @Column annotation to map the table column name image_uri to the property name imageUri.
In the Cloud Shell code editor, open ~/guestbook-service/src/main/java/com/example/guestbook/GuestbookMessage.java.
Replace the entire contents of this file with the following code:
In this task, you update the GuestbookMessageRepository.java file to use String as the ID type.
Spring Data Spanner implements many commonly used Spring Data patterns, such as creating simple methods that can be automatically translated to corresponding SQL queries.
One example is a simple method signature: List<GuestbookMessage> findByName(String name);. The Spring framework enables querying the Spanner table with the SQL query SELECT * FROM guestbook_message WHERE name = ?.
In the Cloud Shell code editor, open ~/guestbook-service/src/main/java/com/example/guestbook/GuestbookMessageRepository.java.
Insert the following import statement after the existing import directives:
import java.util.List;
Change the datatype for the PagingAndSortingRepository GuestbookMessage parameter from Long to String:
public interface GuestbookMessageRepository extends
PagingAndSortingRepository<GuestbookMessage, String> {
}
Insert the following code into the definition for the GuestbookMessageRepository public interface, immediately before the closing brace:
List<GuestbookMessage> findByName(String name);
The GuestbookMessageRepository.java file should now look like the screenshot:
Task 8. Test the backend service application locally in Cloud Shell
In this task, you run the updated guestbook backend service application in Cloud Shell in order to test that the application has been correctly configured to use Spanner for database services.
In Cloud Shell, change to the guestbook-service directory:
cd ~/guestbook-service
Launch the guestbook backend service application locally:
./mvnw spring-boot:run
In a new Cloud Shell tab, use curl to post a message:
Use the gcloud spanner command with a SQL query to validate that messages exist:
gcloud spanner databases execute-sql messages --instance=guestbook \
--sql="SELECT * FROM guestbook_message WHERE name = 'Ray'"
Switch back to the Google Cloud console and navigate to your Spanner guestbook_message table to see the new entry. Click the Spanner Studio tab to see the new entry.
Click the Write DDL, select the editor tab and then execute the given query by clicking Run button:
Select * FROM guestbook_message LIMIT 10
Task 9. Redeploy the backend service application to App Engine
In this task, you redeploy the updated guestbook backend service application to App Engine.
Switch back to the Cloud Shell tab where the guestbook backend service application is running.
Press CTRL+C to stop the application.
Make sure you are in the guestbook-service directory:
cd ~/guestbook-service
Use Apache Maven to rebuild the backend service application redeploy it to App Engine:
mvn package appengine:deploy -DskipTests
When the deployment completes, the output from Maven provides the URL of the updated backend service application:
...
[INFO] GCLOUD: Deployed service [guestbook-service] to [https://guestbook-service-dot-PROJECT_ID.appspot.com]
[INFO] GCLOUD:
[INFO] GCLOUD: You can stream logs from the command line by running:
[INFO] GCLOUD: $ gcloud app logs tail -s guestbook-service
[INFO] GCLOUD:
[INFO] GCLOUD: To view your application in the web browser run:
[INFO] GCLOUD: $ gcloud app browse -s guestbook-service
...
Use the following command to list the URLfor the updated backend service application:
gcloud app browse -s guestbook-service
A clickable URL link to your new backend service appears:
Did not detect your browser. Go to this link to view your app:
https://guestbook-service-dot-....appspot.com
Click the URL link to open the backend guestbook service.
The response lists all the messages in the Spanner database.
Switch back to the browser tab for the frontend application.
Note: If you have closed that tab, use the following command to list the URL for the guestbook frontend application that is running on App Engine:gcloud app browse -s default. Then click the link to browse to the guestbook frontend application.
Enter a message to test that the application is working.
You should now see an updated message list that includes the initial test message you sent from Cloud Shell and the new message you just posted confirming that the updated backend service application is using the new Spanner database.
Task 10. Review
In this lab, you created a Spanner instance and database. You used the data definition language (DDL) to create a Spanner table. You also used Spring to add support for Spanner to an application. Finally, you modified a Java application to use Spanner instead of Cloud SQL.
End your lab
When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
1 star = Very dissatisfied
2 stars = Dissatisfied
3 stars = Neutral
4 stars = Satisfied
5 stars = Very satisfied
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
Lab membuat project dan resource Google Cloud untuk jangka waktu tertentu
Lab memiliki batas waktu dan tidak memiliki fitur jeda. Jika lab diakhiri, Anda harus memulainya lagi dari awal.
Di kiri atas layar, klik Start lab untuk memulai
Gunakan penjelajahan rahasia
Salin Nama Pengguna dan Sandi yang diberikan untuk lab tersebut
Klik Open console dalam mode pribadi
Login ke Konsol
Login menggunakan kredensial lab Anda. Menggunakan kredensial lain mungkin menyebabkan error atau dikenai biaya.
Setujui persyaratan, dan lewati halaman resource pemulihan
Jangan klik End lab kecuali jika Anda sudah menyelesaikan lab atau ingin mengulanginya, karena tindakan ini akan menghapus pekerjaan Anda dan menghapus project
Konten ini tidak tersedia untuk saat ini
Kami akan memberi tahu Anda melalui email saat konten tersedia
Bagus!
Kami akan menghubungi Anda melalui email saat konten tersedia
Satu lab dalam satu waktu
Konfirmasi untuk mengakhiri semua lab yang ada dan memulai lab ini
Gunakan penjelajahan rahasia untuk menjalankan lab
Gunakan jendela Samaran atau browser pribadi untuk menjalankan lab ini. Langkah ini akan mencegah konflik antara akun pribadi Anda dan akun Siswa yang dapat menyebabkan tagihan ekstra pada akun pribadi Anda.
Java Microservices with Spring Boot
Lab 11 Working with Spanner