springboot 多数据源
时间: 2023-09-25 16:15:49 浏览: 171
Spring Boot支持多数据源,可以使用多个数据库进行开发。以下是实现多数据源的步骤:
1. 配置多个数据源
在application.properties文件中配置多个数据源,如:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=root
spring.datasource.password=123456
db2.datasource.url=jdbc:mysql://localhost:3306/db2
db2.datasource.username=root
db2.datasource.password=123456
```
2. 创建多个数据源
使用@Configuration注解创建多个数据源。如下:
```java
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource db1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db2DataSource")
@ConfigurationProperties(prefix = "db2.datasource")
public DataSource db2DataSource() {
return DataSourceBuilder.create().build();
}
}
```
3. 配置数据源的事务管理器
在每个数据源上配置事务管理器。如下:
```java
@Configuration
@EnableTransactionManagement
public class TransactionConfig {
@Bean(name = "db1TransactionManager")
public PlatformTransactionManager db1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "db2TransactionManager")
public PlatformTransactionManager db2TransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
```
4. 在@Repository中使用指定的数据源
在@Repository中指定使用哪个数据源。如下:
```java
@Repository
public class UserRepository {
@Autowired
@Qualifier("db1DataSource")
private DataSource db1DataSource;
@Autowired
@Qualifier("db2DataSource")
private DataSource db2DataSource;
@Autowired
@Qualifier("db1TransactionManager")
private PlatformTransactionManager db1TransactionManager;
@Autowired
@Qualifier("db2TransactionManager")
private PlatformTransactionManager db2TransactionManager;
@PersistenceContext(unitName = "db1")
private EntityManager db1EntityManager;
@PersistenceContext(unitName = "db2")
private EntityManager db2EntityManager;
@Transactional(transactionManager = "db1TransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void addUser(User user) {
EntityManager entityManager = db1EntityManager;
// ...
}
@Transactional(transactionManager = "db2TransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void addUser2(User user) {
EntityManager entityManager = db2EntityManager;
// ...
}
}
```
以上是实现Spring Boot多数据源的步骤,可以根据具体需求进行配置和调整。
阅读全文