我使用 spring boot 应用程序。我通过 JDBC 数据源和存储库从数据库中选择数据。 JDBS 的一些查询和存储库的一些查询。我的数据库配置 RAC 并有 2 个实例。我通过 129.0.0.2
连接到数据库,但此 URL 在 129.0.0.3(1 个实例)和 129.0.0.4(2 个实例)
之间平衡。所有查询都使用 129.0.0.2
执行,但有些查询我只需要在一个实例上执行。我创建了 3 个数据源:
@Bean(name = "primary")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "second")
@ConfigurationProperties(prefix = "spring.secondDatasource")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "three")
@ConfigurationProperties(prefix = "spring.threeDatasource")
public DataSource threeDataSource() {
return DataSourceBuilder.create().build();
}
并在 application.properties 中配置它们。然后我可以写
@Qualifier("primary")DataSource dataSource
或
@Qualifier("second")DataSource dataSource
但是当我执行存储库查询时,DataSource 将使用什么?
最佳答案
像这样创建两个配置类:
@Configuration
@EnableJpaRepositories(basePackages = "your.package.repositories.datasource1",
entityManagerFactoryRef = entityManagerFactory1)
class DataSource1Configuration {
@Bean
public EntityManagerFactory entityManagerFactory1(@Qualifier("primary") DataSource primary) {
// … create entity manager factory based on primary source
}
}
第二个配置类显然相似,但为使用辅助数据源而量身定制
顺便说一句,从 Java 8 开始,也可以在同一个类上有两个类型的注释(在这种情况下是两个 @EnableJpaRepositories
)。因此它也可以使用一个配置类,但使用两个 @EnableJpaRepositories
注释。
关于java - 如何在 Spring Boot 中为不同的数据源配置 JPA 存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41584275/