简体   繁体   English

如何在 Spring Boot 中动态更改数据库?

[英]How to change database dynamically in Spring Boot?

How can we change database credentials and sources in Spring Boot project on run time or you can say dynamically?我们如何在运行时更改 Spring 启动项目中的数据库凭据和源,或者您可以动态地说? Let suppose if we are deploying to test server, database connection in API project point to test database, and if deploy to production server, database automatically point to production server.假设如果我们部署到测试服务器,API 项目中的数据库连接指向测试数据库,如果部署到生产服务器,数据库自动指向生产服务器。 Do some research what kind of config we need to set these settings in our spring boot project.做一些研究,我们需要在 spring 引导项目中设置这些设置。 Technically our project will switch to more than one database connections dynamically.从技术上讲,我们的项目将动态切换到多个数据库连接。

How all this process will happen in Spring boot?所有这些过程将如何在 Spring 引导中发生?

Let suppose if we are deploying to test server, database connection in API project point to test database, and if deploy to production server, database automatically point to production server.假设如果我们部署到测试服务器,API 项目中的数据库连接指向测试数据库,如果部署到生产服务器,数据库自动指向生产服务器。

There're couple of ways.有几种方法。 The first you can provide the properties values as part of env variables.首先,您可以将属性值作为环境变量的一部分提供。 Ex:前任:

-Ddb_url=jdbc:mysql://<server>:<port>/<databasename> -Ddb_username=root -Ddb_password=mysql

spring.datasource.url=${db_url}
spring.datasource.username=${db_username}
spring.datasource.password=${db_password}

or或者

You can use different properties files in accordance with different envs.您可以根据不同的环境使用不同的属性文件。

application.properties
application-test.properties
application-prod.properties

In these properties file you can pre-configured the addresses as per the profile.在这些属性文件中,您可以根据配置文件预先配置地址。 To activate the profile for particular env, you've to provide the following prop to springboot application.要激活特定环境的配置文件,您必须向 springboot 应用程序提供以下道具。 Ex:前任:

-Dspring.profiles.active=prod

In this case, application.properties file will be used first to configured the properties and then the properties from application-prod.properties will be configured.在这种情况下,将首先使用application.properties文件来配置属性,然后再配置application-prod.properties中的属性。 In case of matching properties in both the files, the later file's properties will override the properties in the default property file ie application.properties .如果两个文件中的属性匹配,则后面文件的属性将覆盖默认属性文件中的属性,即application.properties

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM