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

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

PostgreSQL中rank()窗口函数实用指南与示例

《PostgreSQL中rank()窗口函数实用指南与示例》在数据分析和数据库管理中,经常需要对数据进行排名操作,PostgreSQL提供了强大的窗口函数rank(),可以方便地对结果集中的行进行排名... 目录一、rank()函数简介二、基础示例:部门内员工薪资排名示例数据排名查询三、高级应用示例1. 每