SpringCloud集成AlloyDB的示例代码

2025-01-10 16:50

本文主要是介绍SpringCloud集成AlloyDB的示例代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《SpringCloud集成AlloyDB的示例代码》AlloyDB是GoogleCloud提供的一种高度可扩展、强性能的关系型数据库服务,它兼容PostgreSQL,并提供了更快的查询性能...

1.AlloyDB是什么?

AlloyDB 是 Google Cloud 提供的一种高度可扩展、强性能的关系型数据库服务,它兼容 PostgreSQL,并提供了更快的查询性能和更高的可用性。AlloyDB 主要适用于需要处理复杂查询、高吞吐量和对数据库性能要求严格的应用场景。

AlloyDB 的工作原理

AlloyDB 是建立在 Google Cloud 的分布式架构上的,具有以下特点:

  • 高性能:通过在内存中缓存热数据和优化查询执行,AlloyDB 提供比传统 PostgreSQL 快四倍的性能。
  • 高可用性:支持跨区域的高可用部署,具备内置的自动故障转移功能。
  • 兼容性:完全兼容 PostgreSQL,使得现有 PostgreSQL 应用可以无缝迁移。
  • 可管理性:简化了运维工作,通过 Google Cloud 平台的工具进行统一管理。

2.搭建测试环境

参照这个文档在google cloud上创建数据库

cloud.google.com

3.代码工程

Spring Cloud 提供了 spring-cloud-gcp-starter-alloydb 模块,用于简化与 AlloyDB 的集成。通过此模块,您可以轻松配置并连接到 AlloyDB 实例。

以下是一个完整的示例,演示如何使用 Spring Boot 应用程序连接到 AlloyDB。

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-dependencieChina编程s</artifactId>
                <version>5.9.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        <javascript/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>
            &ljavascriptt;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. 配置 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-idyour-regionyour-cluster-idyour-instance-idyour-usernameyour-passwordyour-database-name 替换为实际值。

3. 编写实启动类

创建启动类:

/** Sample application. */
@SpringBootApplication
public class AlloyDbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AlloyDbApplication.class, args);
  }
}

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 andandroid
 * 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());
  }
}

5. 运行应用程序

确保您的 Google Cloud 项目已启用 AlloyDB API,并配置了必要的权限。

  • 在本地运行应用程序时,确保设置了 Google Cloud 的服务账号凭据:

    export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-service-account-key.json

  • 部署到 Google Cloud 时,建议使用 Compute Engine 或 Kubernetes Engine,其内置身份验证会自动获取凭据。

以上只是一些关键代码。

4.测试

应用程序启动后,在浏览器中导航到 http://localhost:8080/getTuples,或使用 Cloud Shell 中的 Web Preview 按钮在端口 8080 上预览应用程序。这将打印用户表的内容。

以上就是SpringCloud集成AlloyDB的示例代码的详细内容,更多关于SpringCloud集成AlloyDB的资料请关注China编程(www.chinasem.cn)其它相关文章!

这篇关于SpringCloud集成AlloyDB的示例代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153019

相关文章

SpringBoot项目启动后自动加载系统配置的多种实现方式

《SpringBoot项目启动后自动加载系统配置的多种实现方式》:本文主要介绍SpringBoot项目启动后自动加载系统配置的多种实现方式,并通过代码示例讲解的非常详细,对大家的学习或工作有一定的... 目录1. 使用 CommandLineRunner实现方式:2. 使用 ApplicationRunne

在Pandas中进行数据重命名的方法示例

《在Pandas中进行数据重命名的方法示例》Pandas作为Python中最流行的数据处理库,提供了强大的数据操作功能,其中数据重命名是常见且基础的操作之一,本文将通过简洁明了的讲解和丰富的代码示例,... 目录一、引言二、Pandas rename方法简介三、列名重命名3.1 使用字典进行列名重命名3.编

基于Java实现模板填充Word

《基于Java实现模板填充Word》这篇文章主要为大家详细介绍了如何用Java实现按产品经理提供的Word模板填充数据,并以word或pdf形式导出,有需要的小伙伴可以参考一下... Java实现按模板填充wor编程d本文讲解的需求是:我们需要把数据库中的某些数据按照 产品经理提供的 word模板,把数据

Python使用Colorama库美化终端输出的操作示例

《Python使用Colorama库美化终端输出的操作示例》在开发命令行工具或调试程序时,我们可能会希望通过颜色来区分重要信息,比如警告、错误、提示等,而Colorama是一个简单易用的Python库... 目录python Colorama 库详解:终端输出美化的神器1. Colorama 是什么?2.

使用IntelliJ IDEA创建简单的Java Web项目完整步骤

《使用IntelliJIDEA创建简单的JavaWeb项目完整步骤》:本文主要介绍如何使用IntelliJIDEA创建一个简单的JavaWeb项目,实现登录、注册和查看用户列表功能,使用Se... 目录前置准备项目功能实现步骤1. 创建项目2. 配置 Tomcat3. 项目文件结构4. 创建数据库和表5.

Go Gorm 示例详解

《GoGorm示例详解》Gorm是一款高性能的GolangORM库,便于开发人员提高效率,本文介绍了Gorm的基本概念、数据库连接、基本操作(创建表、新增记录、查询记录、修改记录、删除记录)等,本... 目录1. 概念2. 数据库连接2.1 安装依赖2.2 连接数据库3. 数据库基本操作3.1 创建表(表关

Python视频剪辑合并操作的实现示例

《Python视频剪辑合并操作的实现示例》很多人在创作视频时都需要进行剪辑,本文主要介绍了Python视频剪辑合并操作的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习... 目录介绍安装FFmpegWindowsMACOS安装MoviePy剪切视频合并视频转换视频结论介绍

python多进程实现数据共享的示例代码

《python多进程实现数据共享的示例代码》本文介绍了Python中多进程实现数据共享的方法,包括使用multiprocessing模块和manager模块这两种方法,具有一定的参考价值,感兴趣的可以... 目录背景进程、进程创建进程间通信 进程间共享数据共享list实践背景 安卓ui自动化框架,使用的是

Java文件上传的多种实现方式

《Java文件上传的多种实现方式》文章主要介绍了文件上传接收接口的使用方法,包括获取文件信息、创建文件夹、保存文件到本地的两种方法,以及如何使用Postman进行接口调用... 目录Java文件上传的多方式1.文件上传接收文件接口2.接口主要内容部分3.postman接口调用总结Java文件上传的多方式1

使用SpringBoot创建一个RESTful API的详细步骤

《使用SpringBoot创建一个RESTfulAPI的详细步骤》使用Java的SpringBoot创建RESTfulAPI可以满足多种开发场景,它提供了快速开发、易于配置、可扩展、可维护的优点,尤... 目录一、创建 Spring Boot 项目二、创建控制器类(Controller Class)三、运行