gpt4 book ai didi

java - 以编程方式在本地数据库和 Google Cloud SQL 之间切换

转载 作者:行者123 更新时间:2023-11-30 01:40:58 25 4
gpt4 key购买 nike

我正在 Spring Boot 中开发一个项目,到目前为止该项目仅使用本地 Postgres 数据库。不过,我们现在正致力于将应用程序部署到 Google 云平台,其中涉及使用 Cloud SQL。我找到了一些有关如何连接到 Cloud SQL 的指南,并决定遵循 this one

但是,我们无法承担在 Cloud SQL 中运行单独的开发数据库的费用,因此希望继续使用本地 Postgres 数据库进行开发。为此,我编写了以下代码:

@Configuration
@EnableTransactionManagement
public class PersistenceContext {
@Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(System.getenv("DB_URL"));
dataSource.setUsername(System.getenv("DB_USER"));
dataSource.setPassword(System.getenv("DB_PASS"));

String dbInstance = System.getenv("DB_INSTANCE");

if (dbInstance != null && !dbInstance.isEmpty()) {
Properties connectionProperties = new Properties();
connectionProperties
.setProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory");
connectionProperties.setProperty("cloudSqlInstance", dbInstance);

dataSource.setConnectionProperties(connectionProperties);
}

return dataSource;
}
}

有了这个,我希望只要不指定云 SQL 套接字工厂和 dbInstance 就可以让我使用本地数据库。但是,当尝试仅使用数据库 URL、用户和密码变量集运行应用程序时,我遇到了以下异常:

java.lang.IllegalArgumentException: An instance connection name must be provided in the format <PROJECT_ID>:<REGION>:<INSTANCE_ID>.

可以找到完整的堆栈跟踪 here

数据库 URL 配置如下:

DB_URL:jdbc:postgresql://localhost:5432/soundshare

如何以编程方式在数据库之间切换? (如果可以避免,我宁愿不要将数据库详细信息存储在配置文件中)

谢谢!

最佳答案

因此,正如 @Thomas Andolf 所说,自己用代码来做这件事并不是一个好主意,基本上是重新发明轮子。有多种方法可以“外部化”您的配置。

https://docs.spring.io/spring-boot/docs/1.2.2.RELEASE/reference/html/boot-features-external-config.html

就我个人而言,我喜欢尽可能使用操作系统环境变量,因为当我部署为容器时,我也可以轻松地进行交换。

这是我正在处理的项目的 application.properties 文件的横截面:

spring.datasource.url=${ospec_db_url} spring.datasource.username=${ospec_db_user:somedefault} spring.datasource.password=${ospec_db_password}

在我的开发系统上,我只需设置环境变量,它就会被拾取。就我而言,我有一个包含变量的文本文件,如下所示:

export ospec_db_url=jdbc:postgresql://localhost:5432/ospec_db
export ospec_db_password=somebadasspassword

我只是获取文本文件并应用它。我可以轻松地在项目之间切换来执行此操作。当您打包 K8s 时,您可以从 secret 文件读取到您的环境变量,当您转到云时,您可以将这些值作为启动脚本中的变量传递。

关于java - 以编程方式在本地数据库和 Google Cloud SQL 之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com