Spring Boot整合MyBatis Plus集成多数据源轻松实现数据读写分离
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource primaryDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(primaryDataSource);
return sqlSessionFactoryBean.getObject();
}
@Bean
public MybatisSqlSessionTemplate mybatisSqlSessionTemplate(
@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new MybatisSqlSessionTemplate(sqlSessionFactory);
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory secondarySqlSessionFactory(DataSource secondaryDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(secondaryDataSource);
return sqlSessionFactoryBean.getObject();
}
@Bean(name = "secondaryMybatisSqlSessionTemplate")
public MybatisSqlSessionTemplate secondaryMybatisSqlSessionTemplate(
@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new MybatisSqlSessionTemplate(sqlSessionFactory);
}
}
这个配置类定义了两个数据源primaryDataSource
和secondaryDataSource
,并为每个数据源创建了对应的SqlSessionFactory
和MybatisSqlSessionTemplate
。通过使用@Qualifier
注解,你可以在需要的地方注入特定的SqlSessionFactory
或SqlSessionTemplate
。这样,你就可以根据业务需要选择使用哪一个数据源来执行数据库操作。
评论已关闭