在Spring Boot中配置主从数据库可以通过在application.properties文件中配置多个数据源来实现。以下是一个示例配置:
1、在application.properties中配置主数据源:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/main_db
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
2、在application.properties中配置从数据源:
```properties
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db
spring.datasource.secondary.username=root
spring.datasource.secondary.password=password
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
```
3、创建配置类来定义多数据源配置:
```java
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "mainDataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource mainDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
```
4、在Repository中指定数据源:
```java
@Repository
public class MainRepository {
@Autowired
@Qualifier("mainDataSource")
private DataSource dataSource;
// Repository methods
}
@Repository
public class SecondaryRepository {
@Autowired
@Qualifier("secondaryDataSource")
private DataSource dataSource;
// Repository methods
}
```
通过以上步骤,就可以在Spring Boot中配置主从数据库并在Repository中使用不同的数据源进行操作。