This code sample demonstrates how to connect to a MySQL Google Cloud SQL instance using the Spring Cloud GCP MySQL Starter.
You will create an instance, a database within the instance, populate the database and then query it.
You can also explore the GCP MySQL Starter in the Spring Pet Clinic using Cloud SQL codelab.
-
Follow these instructions to set up a Google Cloud Project with billing enabled.
-
Create a Google Cloud MySQL instance from the Google Cloud Console Cloud SQL page.
-
Still within the Google Cloud Console SQL page, create a new database in the instance from the "Databases" section. If you decided to set a root password for your instance [1], then don’t forget to take note of your root password, as you will need it in the next step!
-
Open the application.properties file and replace [database-name] with the name of the database you created in step 3 and [instance-connection-name] with the instance connection name of the instance you created in step 1.
If you set a root password, add the
spring.datasource.password
property with the root password as the value.If you would like to use a different user, set the
spring.datasource.username
property appropriately. -
If you are authenticated in the Cloud SDK, your credentials will be automatically found by the Spring Boot Starter for Google Cloud SQL.
Alternatively, create a service account from the Google Cloud Console and download its private key. Then, uncomment the
spring.cloud.gcp.sql.credentials.location
property in the application.properties file and fill its value with the path to your service account private key on your local file system, prepended withfile:
.
You can run the SqlApplication
Spring Boot app using the following command:
$ mvn spring-boot:run
The database will be populated based on the schema.sql and data.sql files.
When the application is up, navigate to http://localhost:8080/getTuples in your browser to print the contents of the users
table.