sprinyboot对接多数据源
时间: 2024-05-09 08:16:36 浏览: 30
Spring Boot对接多数据源可以通过配置多个数据源和事务管理器来实现。以下是一个简单的例子:
1.在application.properties中配置多个数据源
```
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/primary
spring.datasource.primary.username=primary_user
spring.datasource.primary.password=primary_password
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/secondary
spring.datasource.secondary.username=secondary_user
spring.datasource.secondary.password=secondary_password
```
2.创建多个数据源的配置类
```
@Configuration
public class PrimaryDataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
}
@Configuration
public class SecondaryDataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
```
3.配置事务管理器
```
@Configuration
@EnableTransactionManagement
public class TransactionConfig {
@Bean
@Primary
public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
```
4.在需要使用数据源的地方指定数据源
```
@Service
@Transactional(transactionManager = "primaryTransactionManager")
public class PrimaryService {
// ...
}
@Service
@Transactional(transactionManager = "secondaryTransactionManager")
public class SecondaryService {
// ...
}
```
以上是一个简单的多数据源配置示例,具体实现可以根据实际需求进行调整。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)