根据会话的环境参数,设置Spring Boot应用程序以连接到不同的数据源



我目前正在构建一个Spring Boot应用程序,该应用程序需要与三种不同的数据库环境一起工作,并以与环境无关的方式工作。

  • "dev"环境将使用本地sqlite数据库。

  • "uat"环境将使用postgres数据库。

  • "实时"环境将使用sql数据库。

加载时,我的应用程序检查是否存在环境参数:

  • 如果未设置任何属性或环境参数为dev,则它将创建一个本地sqlite数据库,并在会话期间与其建立连接。

  • 如果它被设置为uat,那么将建立到heroku-postgres数据库的连接。

  • 如果它被设置为live,那么将建立到mysql数据库的连接。

现在我正在Java上努力将其概念化。

这是我到目前为止写的代码,在这里我得到了环境参数。除此之外,我不确定该怎么做。

@SpringBootApplication
public class Launcher implements CommandLineRunner {
public static void main(String args[]) {
SpringApplication.run(Launcher.class, args);
}
@Override
public void run(String... args) throws Exception {
String currentEnvironment = System.getenv("CURRENT_ENV");
// if current env is null or dev, set up sqlite database (if it doesnt already exist and use this for the remainder of the session
// if uat connect to heroku postgres db
// if live then connect to mysql db
}
}

这是在spring中创建概要文件的目的,spring Boot允许您拥有有助于应用程序在不同环境中运行的概要文件。

因此,在您的情况下,您必须创建三个属性文件,例如

  1. dev.properties
  2. uat.properties
  3. live.properties

在每个属性文件中,您必须设置开发所需的配置。然后只需激活您想要使用的配置文件。

spring.profiles.active=dev

对于每一个,我都会创建一个@Configuration类。

@Profile("dev")
@Configuration
public class DevConfiguration{
...
}
@Profile("uat")
@Configuration
public class UatConfiguration{
...
}
@Profile("live")
@Configuration
public class LiveConfiguration{
...
}

我想提到Felipe Gutierrez的一本好书《Pro Spring Boot》,它可以教会你很多。

我认为真正的问题是:如何指定环境?

使用Spring引导,您可以使用多个应用程序属性文件。在您的情况下,您可以使用3个文件:

  • application.properties(用于开发环境(
  • application-uat.properties(用于uat-env(
  • application-live.properties(用于实时环境(

您也可以使用YAML文件来执行此操作。

有很多方法可以让SpringBoot选择正确的环境属性文件。

有很多方法可以选择正确的环境文件。

例如,如果对每个环境使用tomcat,则可以设置属性spring.profiles.active例如JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=ENV_NAME"(在setclasspath.bat中(如果您在[l]unix上,则为setclasspath.sh(,其中ENV_NAME可以是uat或live。

相关内容

最新更新