This code sample demonstrates how to connect to a Postgres Google Cloud SQL instance using the Spring Cloud GCP PostgreSQL Starter. If you are interested in MySQL as well, you may refer to the MySQL sample app.
You will create an instance, a database within the instance, populate the database and then query it.
-
Follow these instructions to set up a Google Cloud Project with billing enabled.
-
Create a Google Cloud SQL instance from the Google Cloud Console Cloud SQL page. Choose "Postgres" as your database engine. You will be asked to set a password for the
postgres
root user; remember this value. -
Still within the Google Cloud Console SQL page, create a new database in the instance from the "Databases" section.
-
Open the application.properties file and set the following properties:
-
spring.datasource.password
- Set this to the password that you chose for thepostgres
user. -
spring.cloud.gcp.sql.database-name
- Set this to the name of the database you created. -
spring.cloud.gcp.sql.instance-connection-name
- Set this to the instance name of your Postgres instance. The instance-connection-name should be in the form:[gcp-project-id]:[region]:[instance-name]
.For example, your instance connection name might look like:
my-gcp-project:us-central1:postgres-test-instance
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.credentials.location
property in the link:src/main/resources/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.