一、需求
假设我们原本只查询单个环境的mysql库数据,现在如果想进行改造该如何支持查询多个环境的mysql库的数据呢?
二、需要准备的环境
两台mysql数据库服务器:
Host1:192.168.25.134
Host2:192.168.25.166
三、配置文件修改
修改application.properties的内容,多个数据库的配置名需要保证唯一
bash
#三套环境
spring.datasource.api3.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.api3.sql-script-encoding=utf-8
spring.datasource.api3.url=jdbc:mysql://192.168.25.134:3306/api?allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.api3.username=api
spring.datasource.api3.password=apiapi
#四套环境
spring.datasource.api4.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.api4.sql-script-encoding=utf-8
spring.datasource.api4.url=jdbc:mysql://192.168.25.166:3306/api?allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.api4.username=api
spring.datasource.api4.password=apiapi
四、配置代码修改
代码中配置多个数据源
java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.api3")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.api4")
public DataSource dataSource3() {
return DataSourceBuilder.create().build();
}
}
创建多个数据源对应的bean对象
java
@Configuration
@MapperScan(basePackages = "com.icbc.ndf.jft.manager.mapper3", sqlSessionFactoryRef = "sqlSessionFactory2")
public class MyBatisConfig2 {
@Autowired
@Qualifier("dataSource2")
private DataSource dataSource2;
@Bean
public SqlSessionFactory sqlSessionFactory2() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource2);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory2());
}
}
java
@Configuration
@MapperScan(basePackages = "com.icbc.ndf.jft.manager.mapper4", sqlSessionFactoryRef = "sqlSessionFactory3")
public class MyBatisConfig3 {
@Autowired
@Qualifier("dataSource3")
private DataSource dataSource3;
@Bean
public SqlSessionFactory sqlSessionFactory3() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource3);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate3() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory3());
}
}
五、创建多个mapper目录
每个mapper目录下对应不同数据库的mapper及mapper.xml文件。这里以mapper作为示例。在mapper3和mapper4下分别创建ApiResExtendMapper3 和ApiResExtendMapper4 ,以及对应的xml文件
java
@Mapper
public interface ApiResExtendMapper3 {
/**
* 通过实体作为筛选条件查询
*
* @param apiResExtend 实例对象
* @return 对象列表
*/
List<ApiResExtend> queryByUrl(ApiResExtend apiResExtend);
}
java
@Mapper
public interface ApiResExtendMapper4 {
/**
* 通过实体作为筛选条件查询
*
* @param apiResExtend 实例对象
* @return 对象列表
*/
List<ApiResExtend> queryByUrl(ApiResExtend apiResExtend);
}
这样我们就完成了多数据源的配置,可以启动项目测试了~~