多个数据源配置,并在使用hikari的sping boot 2中使用

时间:2019-03-09 19:29:47

标签: hibernate spring-boot datasource hikaricp

我已经用spring boot配置了两个Postgres数据库,但是spring总是显示主数据库而忽略了辅助数据库,任何帮助将不胜感激。

下面是我的配置

application.properties

#datasource 1
    spring.datasource.url= jdbc:postgresql://localhost:5432/db1
    spring.datasource.username=user1
    spring.datasource.password=user1

#data source 2    
    spring.datasource2.url= jdbc:postgresql://localhost:5432/db2
    spring.datasource2.username=user2
    spring.datasource2.password=user2

下面是数据源1的配置。我在数据源1中有多个存储库和实体,这是我的主要数据源。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "primaryEntityManager",
        transactionManagerRef = "primaryTransactionManager",
        basePackages = {"pkg.user_service.repository","pkg.master.repository","pkg.Wallet.repository","pkg.security.repositories",
                "pkg.product_service.repository","pkg.OMS.repository","pkg.LMS.repository","pkg.payment.repository"}
)    
public class DataSource1_config {  

 @Bean
    @Primary
    @ConfigurationProperties("spring.datasource")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }



      @Primary
        @Bean(name = "primaryEntityManager")
        public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(EntityManagerFactoryBuilder builder) {
            return builder
                        .dataSource(dataSource(null))
                       .packages("pkg") 
                        .persistenceUnit("primaryPU")
                        .build();
        }

      @Primary
        @Bean(name = "primaryTransactionManager")
        public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryEntityManager") EntityManagerFactory entityManagerFactory) {
            return new JpaTransactionManager(entityManagerFactory);
        }


}

datsource2的配置在下面,数据源2中只有一个存储库和实体。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "secondEntityManager",
        transactionManagerRef = "secondTransactionManager",             
        basePackages = {"device_info.repository"}
)

public class DataSource2_config {   

    @Bean 
    @ConfigurationProperties(prefix = "spring.datasource2")
     public HikariDataSource secondSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }


        @Bean(name = "secondEntityManager")
        public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory(EntityManagerFactoryBuilder builder) {
            return builder
                        .dataSource(secondSource(null))
                        .packages(User_Device_Info.class) 
                        .persistenceUnit("secondPU")
                        .build();
        }



        @Bean(name = "secondTransactionManager")
        public PlatformTransactionManager secondTransactionManager(@Qualifier("secondEntityManager") EntityManagerFactory entityManagerFactory) {
            return new JpaTransactionManager(entityManagerFactory);
        }



}

1 个答案:

答案 0 :(得分:0)

我已经完成了一个项目,可以使用您的特定changeSets创建多个dataSources,因此,如果您需要添加另一个dataSource,则只需更改application.yml,而无需更改代码。

配置类

  r.apply {
            try {
                stop()
                release()

            } catch (e: IOException) {
                Log.d(TAG, "media recording failed at stop: $e")
            }
        }

application.yml

@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<Object, Object> 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;
    }

}

查看完整的代码:https://github.com/dijalmasilva/spring-boot-multitenancy-datasource-liquibase