簡體   English   中英

根據會話的環境參數設置 Spring Boot 應用程序以連接到不同的數據源

[英]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 允許您擁有有助於您的應用程序在不同環境中運行的配置文件。

因此,在您的情況下,您必須創建三個屬性文件,例如

  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 boot,您可以使用多個應用程序屬性文件。 在您的情況下,您可以使用 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 ( setclasspath.sh 如果您在 [l ]unix),其中 ENV_NAME 可以是 uat 或 live。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM