application.yml中需要配置多个数据源
spring:
profiles:
active: prod
datasource:
db1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://39.103.226.61:3306/mytest?serverTimezone=GMT%2B8&useSSL=false
username: root
password: 。。。
db2:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://39.103.226.61:3306/springboot?serverTimezone=GMT%2B8&useSSL=false
username: root
password: 。。。
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 30000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
注意:springboot 配置多数据源时,启动出现java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
注册数据源组件
多个数据源的情况下, 我们需要通过配置类,将数据源注册为组件放入 Spring 容器中
@Configuration//标注为配置类
public class DataSourceConfig {
/**
* 数据源1
*/
@Bean//返回值注册为组件
@ConfigurationProperties("spring.datasource.db1")//使用spring.datasource.db1作为前缀的配置
public DataSource db1() {
return DataSourceBuilder.create().build();
}
/**
* 数据源2
*/
@Bean//返回值注册为组件
@ConfigurationProperties("spring.datasource.db2")//使用spring.datasource.db2作为前缀的配置
public DataSource db2() {
return DataSourceBuilder.create().build();
}
}
Mybatis配置
多数据源情况下, MyBatis 中的关键组件 SqlSessionFactory 和 SqlSessionTemplate 也需要单独配置,我们需要为两个数据源分别配置一套组件。
@Configuration
@MapperScan(value = "com.design.boot.mapper.mytest", sqlSessionFactoryRef = "sqlSessionFactory1")
public class Db1MybatisConfig {
@Autowired // 自动装配
@Qualifier("db1") // 指定注入名为db1的组件
private DataSource db1;
@Bean
public SqlSessionFactory sqlSessionFactory1() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(db1);// sqlSessionFactory1使用的数据源为db1
sqlSessionFactoryBean
.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/mytest/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory1());// sqlSessionTemplate1使用的数据源也是关联到db1
}
}
@Configuration
@MapperScan(value = "com.design.boot.mapper.springboot", sqlSessionFactoryRef = "sqlSessionFactory2")
public class Db2MybatisConfig {
@Autowired // 自动装配
@Qualifier("db2") // 指定注入名为db2的组件
private DataSource db2;
@Bean
public SqlSessionFactory sqlSessionFactory2() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(db2);// sqlSessionFactory2使用的数据源为db2
sqlSessionFactoryBean
.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/springboot/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory2());// sqlSessionTemplate2使用的数据源也是关联到db2
}
}
之前启动类上的@MapperScan和yml中的mybatis文件配置需要删除