How to set up liquibase in Spring for multiple data sources?

前端 未结 5 1831
醉话见心
醉话见心 2020-12-25 07:59

I need to set up liquibase for two datasources in Spring, at the moment it seems that only one liquibase set up is possib

5条回答
  •  太阳男子
    2020-12-25 08:37

    I've done a project that I can create multiple dataSources with your specific changeSets, so if you need to add another dataSource, it would just change your application.yml, no longer needing to change the code.

    Configuration class

    @Configuration
    @ConditionalOnProperty(prefix = "spring.liquibase", name = "enabled", matchIfMissing = true)
    @EnableConfigurationProperties(LiquibaseProperties.class)
    @AllArgsConstructor
    public class LiquibaseConfiguration {
    
        private LiquibaseProperties properties;
        private DataSourceProperties dataSourceProperties;
    
        @Bean
        @DependsOn("tenantRoutingDataSource")
        public MultiTenantDataSourceSpringLiquibase liquibaseMultiTenancy(Map dataSources,
                                                                          @Qualifier("taskExecutor") TaskExecutor taskExecutor) {
            // to run changeSets of the liquibase asynchronous
            MultiTenantDataSourceSpringLiquibase liquibase = new MultiTenantDataSourceSpringLiquibase(taskExecutor);
            dataSources.forEach((tenant, dataSource) -> liquibase.addDataSource((String) tenant, (DataSource) dataSource));
            dataSourceProperties.getDataSources().forEach(dbProperty -> {
                if (dbProperty.getLiquibase() != null) {
                    liquibase.addLiquibaseProperties(dbProperty.getTenantId(), dbProperty.getLiquibase());
                }
            });
    
            liquibase.setContexts(properties.getContexts());
            liquibase.setChangeLog(properties.getChangeLog());
            liquibase.setDefaultSchema(properties.getDefaultSchema());
            liquibase.setDropFirst(properties.isDropFirst());
            liquibase.setShouldRun(properties.isEnabled());
            return liquibase;
        }
    
    }
    

    application.yml

    spring:
      dataSources:
        - tenantId: db1
          url: jdbc:postgresql://localhost:5432/db1
          username: postgres
          password: 123456
          driver-class-name: org.postgresql.Driver
          liquibase:
            enabled: true
            default-schema: public
            change-log: classpath:db/master/changelog/db.changelog-master.yaml
        - tenantId: db2
          url: jdbc:postgresql://localhost:5432/db2
          username: postgres
          password: 123456
          driver-class-name: org.postgresql.Driver
        - tenantId: db3
          url: jdbc:postgresql://localhost:5432/db3
          username: postgres
          password: 123456
          driver-class-name: org.postgresql.Driver
    

      Link of repository: https://github.com/dijalmasilva/spring-boot-multitenancy-datasource-liquibase

提交回复
热议问题