【精·超简单】SpringBoot 配置多个数据源(连接多个数据库)
在Spring Boot中配置多个数据源通常涉及以下步骤:
- 配置数据源属性。
- 创建数据源实例。
- 配置
EntityManagerFactory
和TransactionManager
。 - 配置
@Configuration
类来扫描相应的包以使用正确的实体。
以下是一个配置两个数据源的简单示例:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primaryTransactionManager")
public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "secondaryTransactionManager")
public DataSourceTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
在application.properties
或application.yml
中配置数据源:
# Primary Database
spring.datasource.primary.url=jdbc:mysql://localhost:3306/db_primary
spring.datasource.primary.username=root
spring.datasource.primary.password=pass
# Secondary Database
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db_secondary
spring.datasource.secondary.username=root
spring.datasource.secondary.password=pass
确保为每个数据源创建相应的实体和仓库,并在使用时指定正确的事务管理器。
@Repository
public class PrimaryDataRepository {
@Transactional(value = "primaryTransactionManager")
public void someDatabaseOperation() {
// Your database operations
}
}
@Repository
public class SecondaryDataRepository {
@Transactional(value = "secondaryTransactionManager")
public void someDatabaseOperation() {
// Your database operations
}
评论已关闭