Spring boot reset datasource on the fly

前端 未结 3 1969
悲哀的现实
悲哀的现实 2021-02-15 13:36

I am trying to update datasource in Spring Boot when the DB property like DB name, password or hostname changes in the spring configuration file or custom DB property file. When

3条回答
  •  粉色の甜心
    2021-02-15 13:51

    In my project I used multitenancy . Basically I defined several datasources in properties like this:

    primary.datasource.url=jdbc:postgresql://localhost:5432/db_name?currentSchema=schema_name
    primary.datasource.username=user
    primary.datasource.password=password
    primary.datasource.driverClassName=org.postgresql.Driver
    primary.datasource.driver-class-name=org.postgresql.Driver
    
    secondary.datasource.url=jdbc:postgresql://localhost:5432/other_db?currentSchema=schema
    secondary.datasource.username=user
    secondary.datasource.password=password
    secondary.datasource.driverClassName=org.postgresql.Driver
    secondary.datasource.driver-class-name=org.postgresql.Driver
    
    default.datasource.url=jdbc:postgresql://localhost:5432/default_db?currentSchema=public
    default.datasource.username=user
    default.datasource.password=password
    default.datasource.driverClassName=org.postgresql.Driver
    default.datasource.driver-class-name=org.postgresql.Driver
    

    then in configuration class defined multiple datasources:

    @Bean
    @Primary
    @ConfigurationProperties(prefix="primary.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean
    @ConfigurationProperties(prefix="secondary.datasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean
    @ConfigurationProperties(prefix="default.datasource")
    public DataSource defaultDataSource(){
        return DataSourceBuilder.create().build();
    }
    

    and configured multitenancy basing on this and this article.
    Pros:

    • Easy tenant switch which could be triggered manually or even configured to be triggered on some specific header in request (filters).
    • Could be cofigured to switch between schemas or databases.
    • Happens dynamically ( you don't have to restart your beans )

    Cons:

    • You have to define all db possibilities in property file.
    • You have to turn off schema validation because it will go nuts.

提交回复
热议问题