在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中使用不同的數據源進行操作。