1.AlloyDB是什么?
AlloyDB 是 Google Cloud 提供的一种高度可扩展、强性能的关系型数据库服务,它兼容 PostgreSQL,并提供了更快的查询性能和更高的可用性。AlloyDB 主要适用于需要处理复杂查询、高吞吐量和对数据库性能要求严格的应用场景。
AlloyDB 的工作原理
AlloyDB 是建立在 Google Cloud 的分布式架构上的,具有以下特点:
高性能
:通过在内存中缓存热数据和优化查询执行,AlloyDB 提供比传统 PostgreSQL 快四倍的性能。
高可用性
:支持跨区域的高可用部署,具备内置的自动故障转移功能。
兼容性
:完全兼容 PostgreSQL,使得现有 PostgreSQL 应用可以无缝迁移。
可管理性
:简化了运维工作,通过 Google Cloud 平台的工具进行统一管理。
2.搭建测试环境
参照这个文档在google cloud上创建数据库
https://cloud.google.com/alloydb/docs/quickstart/integrate-cloud-run
3.代码工程
Spring Cloud 提供了 spring-cloud-gcp-starter-alloydb 模块,用于简化与 AlloyDB 的集成。通过此模块,您可以轻松配置并连接到 AlloyDB 实例。
以下是一个完整的示例,演示如何使用 Spring Boot 应用程序连接到 AlloyDB。
3.1 添加 Maven 依赖
在项目的 pom.xml
文件中添加以下依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>spring-cloud-gcp</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>spring-cloud-gcp-alloydb-sample</artifactId><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>spring-cloud-gcp-dependencies</artifactId><version>5.9.0</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>spring-cloud-gcp-starter-alloydb</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Test-related dependencies. --><dependency><groupId>org.awaitility</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>org.springframework.boot</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>
3.2 配置 AlloyDB 数据源
在 application.properties 或 application.yml 文件中配置 AlloyDB 实例的连接信息:
# Set to the Postgres user you want to connect to; 'postgres' is the default user.
spring.datasource.username=postgres
spring.datasource.password=123456
# spring.cloud.gcp.project-id=spring.cloud.gcp.alloydb.database-name=postgres# This value is formatted in the form: projects/PROJECT_ID/locations/REGION_ID/clusters/CLUSTER_ID/instances/INSTANCE_ID
spring.cloud.gcp.alloydb.instance-connection-uri=projects/PROJECT_ID/locations/REGION_ID/clusters/CLUSTER_ID/instances/INSTANCE_ID# The IP type options are: PRIVATE (default), PUBLIC, PSC.
#spring.cloud.gcp.alloydb.ip-type=PUBLIC
# spring.cloud.gcp.alloydb.target-principal=【your-service-account-email】
# spring.cloud.gcp.alloydb.delegates=[delegates]
# spring.cloud.gcp.alloydb.admin-service-endpoint=[admin-service-endpoint]
#spring.cloud.gcp.alloydb.quota-project=feisty-truth-447013-m7
# spring.cloud.gcp.alloydb.enable-iam-auth=true
# spring.cloud.gcp.alloydb.named-connector=[named-connector]
#spring.cloud.gcp.alloydb.credentials.location=file:///Users/liuhaihua/Downloads/feisty-truth-447013-m7-db149f9a2f86.json# So app starts despite "table already exists" errors.
spring.sql.init.continue-on-error=true
# Enforces database initialization
spring.sql.init.mode=always# Set the logging level
logging.level.root=DEBUG
将 your-project-id、your-region、your-cluster-id、your-instance-id、your-username、your-password 和 your-database-name 替换为实际值。
3.3 编写实启动类
创建启动类:
/** Sample application. */
@SpringBootApplication
public class AlloyDbApplication {public static void main(String[] args) {SpringApplication.run(AlloyDbApplication.class, args);}
}
3.4 编写控制器
创建一个控制器来测试数据库连接:
/** 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** https://www.apache.org/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 com.et;import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
import java.util.stream.Collectors;/** Web app controller for sample app. */
@RestController
public class WebController {private final JdbcTemplate jdbcTemplate;public WebController(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}@GetMapping("/getTuples")public List<String> getTuples() {return this.jdbcTemplate.queryForList("SELECT * FROM users").stream().map(m -> m.values().toString()).collect(Collectors.toList());}
}
3.5 运行应用程序
确保您的 Google Cloud 项目已启用 AlloyDB API,并配置了必要的权限。
在本地运行应用程序时,确保设置了 Google Cloud 的服务账号凭据:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-service-account-key.json
部署到 Google Cloud 时,建议使用 Compute Engine 或 Kubernetes Engine,其内置身份验证会自动获取凭据。
以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库
https://github.com/Harries/springcloud-demo(Spring Cloud GCP/spring-cloud-gcp-alloydb-sample)
4.测试
应用程序启动后,在浏览器中导航到 http://localhost:8080/getTuples,或使用 Cloud Shell 中的 Web Preview 按钮在端口 8080 上预览应用程序。这将打印用户表的内容。
5.引用
https://github.com/GoogleCloudPlatform/spring-cloud-gcp/tree/main/spring-cloud-gcp-samples/spring-cloud-gcp-alloydb-sample
https://www.liuhaihua.cn/archives/712071.html
原创 Harrieis HBLOG