What is it?
AlloyDB is a highly scalable, highly performant relational database service provided by Google Cloud. It is compatible with PostgreSQL and provides faster query performance and higher availability. AlloyDB is mainly suitable for application scenarios that need to handle complex queries, high throughput, and strict database performance requirements.
How AlloyDB works
AlloyDB is built on the distributed architecture of Google Cloud and has the following characteristics:
- high performance: By caching hot data in memory and optimizing query execution, AlloyDB provides four times faster performance than traditional PostgreSQL.
- High availability: Supports high availability across regions and has built-in automatic failover function.
- compatibility: Fully compatible with PostgreSQL, allowing existing PostgreSQL applications to be migrated seamlessly.
- Manageability: Simplified operation and maintenance work and unified management through the tools of the Google Cloud platform.
2. Build a test environment
Refer to this document to create a database on Google Cloud
3. Code Engineering
Spring Cloud providesspring-cloud-gcp-starter-alloydb
Module for simplifying integration with AlloyDB. This module allows you to easily configure and connect to your AlloyDB instance.
Here is a complete example of how to connect to AlloyDB using a Spring Boot application.
1. Add Maven dependencies
On the projectAdd the following dependencies to the file:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0."> <parent> <artifactId>spring-cloud-gcp</artifactId> <groupId></groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>spring-cloud-gcp-alloydb-sample</artifactId> <properties> <>17</> <>17</> </properties> <dependencyManagement> <dependencies> <dependency> <groupId></groupId> <artifactId>spring-cloud-gcp-dependencies</artifactId> <version>5.9.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId></groupId> <artifactId>spring-cloud-gcp-starter-alloydb</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Test-related dependencies. --> <dependency> <groupId></groupId> <artifactId>awaitility</artifactId> <version>4.2.2</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.17.0</version> <scope>test</scope> </dependency> </dependencies> </project>
2. Configure the AlloyDB data source
existor
Connection information for the AlloyDB instance configured in the file:
# Set to the Postgres user you want to connect to; 'postgres' is the default user. =postgres =123456 # -id= -name=postgres # This value is formatted in the form: projects/PROJECT_ID/locations/REGION_ID/clusters/CLUSTER_ID/instances/INSTANCE_ID -connection-uri=projects/PROJECT_ID/locations/REGION_ID/clusters/CLUSTER_ID/instances/INSTANCE_ID # The IP type options are: PRIVATE (default), PUBLIC, PSC. #-type=PUBLIC # -principal=【your-service-account-email】 # =[delegates] # -service-endpoint=[admin-service-endpoint] #-project=feisty-truth-447013-m7 # -iam-auth=true # -connector=[named-connector] #=file:///Users/liuhaihua/Downloads/ # So app starts despite "table already exists" errors. -on-error=true # Enforces database initialization =always # Set the logging level =DEBUG
Willyour-project-id
、your-region
、your-cluster-id
、your-instance-id
、your-username
、your-password
andyour-database-name
Replace with the actual value.
3. Write a realistic startup class
Create a startup class:
/** Sample application. */ @SpringBootApplication public class AlloyDbApplication { public static void main(String[] args) { (, args); } }
4. Write a controller
Create a controller to test the database connection:
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * /licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ; import ; import ; import ; import ; import ; /** Web app controller for sample app. */ @RestController public class WebController { private final JdbcTemplate jdbcTemplate; public WebController(JdbcTemplate jdbcTemplate) { = jdbcTemplate; } @GetMapping("/getTuples") public List<String> getTuples() { return ("SELECT * FROM users").stream() .map(m -> ().toString()) .collect(()); } }
5. Run the application
Make sure your Google Cloud project has the AlloyDB API enabled and the necessary permissions are configured.
-
When running the application locally, make sure that the service account credentials for Google Cloud are set:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/
When deploying to Google Cloud, it is recommended to use Compute Engine or Kubernetes Engine, whose built-in authentication automatically obtains credentials.
The above are just some key codes.
4. Test
Once the application starts, navigate to http://localhost:8080/getTuples in the browser, or preview the application on port 8080 using the Web Preview button in Cloud Shell. This will print the contents of the user table.
The above is the detailed content of the sample code for SpringCloud integrating AlloyDB. For more information about SpringCloud integrating AlloyDB, please follow my other related articles!