How to configure master-slave databases in Spring Boot?
In Spring Boot, configuring master-slave databases can be achieved by setting up multiple data sources in the application.properties file. Here is an example configuration:
Configure the main data source in the application.properties file.
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
Configure the data source in the application.properties file.
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. Create a configuration class to define multiple data source configurations.
@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();
}
}
Specify the data source in the Repository.
@Repository
public class MainRepository {
@Autowired
@Qualifier("mainDataSource")
private DataSource dataSource;
// Repository methods
}
@Repository
public class SecondaryRepository {
@Autowired
@Qualifier("secondaryDataSource")
private DataSource dataSource;
// Repository methods
}
By following the steps above, it is possible to configure master-slave databases in Spring Boot and use different data sources in the Repository for operations.
More tutorials
Tutorial on how to set up a Hibernate Tomcat JNDI DataSource.(Opens in a new browser tab)
What is the principle behind Redis master-slave replication?(Opens in a new browser tab)
Spring Boot CLI(Opens in a new browser tab)
How to use databases in PyQt5?(Opens in a new browser tab)
How does user permission management work in Hive?(Opens in a new browser tab)