[英]Setup Spring Boot application to connect to different data source depending on environment parameter for the session
我目前正在构建一个 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 允许您拥有有助于您的应用程序在不同环境中运行的配置文件。
因此,在您的情况下,您必须创建三个属性文件,例如
dev.properties
uat.properties
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 boot,您可以使用多个应用程序属性文件。 在您的情况下,您可以使用 3 个文件:
您也可以使用 YAML 文件来执行此操作。
有很多方法可以让 SpringBoot 选择正确的环境属性文件。
您有很多方法可以选择正确的环境文件。
例如,如果在每个环境中使用 tomcat,您可以设置属性 spring.profiles.active 例如JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=ENV_NAME"
(在 setclasspath.bat ( setclasspath.sh 如果您在 [l ]unix),其中 ENV_NAME 可以是 uat 或 live。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.