springboot:整合多数据源
Posted cdwxs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot:整合多数据源相关的知识,希望对你有一定的参考价值。
数据源是如何划分:
按包名(业务)和注解划分 ;例如:com.test.learn01----使用datasource1; com.test.learn02----使用datasource2。
项目目录结构:
配置文件中新增两个数据源
创建数据源DataSource1Config
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.learn.datasource1", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config {
@Bean(name = "test1DataSource")
// 以spring.datasource.test1开头去读peroperties文件的数据源信息
@ConfigurationProperties(prefix = "spring.datasource.test1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "test1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
/*
* bean.setMapperLocations( new
* PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"))
* ;
*/
return bean.getObject();
}
@Bean(name = "test1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "test1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
创建数据源DataSource2Config
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.learn.datasource2", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSource2Config {
@Bean(name = "test2DataSource")
// 以spring.datasource.test1开头去读peroperties文件的数据源信息
@ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
/*
* bean.setMapperLocations( new
* PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"))
* ;
*/
return bean.getObject();
}
@Bean(name = "test2TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "test2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
写Mappper接口
service层
以上是关于springboot:整合多数据源的主要内容,如果未能解决你的问题,请参考以下文章
Springboot-整合多数据源配置 & AbstractRoutingDataSource详解,分析多数据源切换原理