前言
配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性。
数据源属性配置
如需配置2个数据源则要在application.yml文件中进行如下配置:
spring:
datasource:
one:
username: db1
password: 123456
jdbc-url: jdbc:mysql://localhost/db1
two:
username: db2
password: 123456
jdbc-url: jdbc:mysql://localhost/db2
数据源属性注入
新建DataSourceConfig类管理多个数据源将配置的属性进行注入并生成Bean
@Configuration
public class DataSourceConfig {
/**
* 数据源1
*/
@Bean
@ConfigurationProperties("spring.datasource.one")
public DataSource dsOne() {
return DataSourceBuilder.create().build();
}
/**
* 数据源2
*/
@Bean
@ConfigurationProperties("spring.datasource.two")
public DataSource dsTwo() {
return DataSourceBuilder.create().build();
}
}
MyBatis配置
新建MyBatisOneConfig和MyBatisTwoConfig管理数据源1和数据源2
@MapperScan注解使对应包下的Mapper使用对应的SqlSessionFactory实例
@Configuration
@MapperScan(value = "com.example.demo.mapper.one", sqlSessionFactoryRef = "sqlSessionFactoryBean1")
public class MyBatisOneConfig {
@Resource
@Qualifier("dsOne")
private DataSource dsOne;
@Bean
public SqlSessionFactory sqlSessionFactoryBean1() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dsOne);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
return new SqlSessionTemplate(sqlSessionFactoryBean1());
}
}
@Configuration
@MapperScan(value = "com.example.demo.mapper.two", sqlSessionFactoryRef = "sqlSessionFactoryBean2")
public class MyBatisTwoConfig {
@Resource
@Qualifier("dsTwo")
private DataSource dsTwo;
@Bean
public SqlSessionFactory sqlSessionFactoryBean2() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dsTwo);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
return new SqlSessionTemplate(sqlSessionFactoryBean2());
}
}
若需要将XML映射文件写在resources目录下可添加如该段代码
org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver()
.getResources("classpath:/mapping/one/*.xml");
factoryBean.setMapperLocations(resources);
创建Mapper和对应的映射文件
在one和two包下创建mapper和对应的映射文件
1.png
在Maven工程中,XML配置文件建议写在resources目录下但上下文的Mapper.xml文件写在包下,Maven在运行时会忽略包下的XML文件,因此需要在pom.xml文件中指明资源文件位置,配置如下
<build>
...
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
...
</build>
注入实例并调用
@RestController
public class DemoController {
@Resource
private BookMapper bookMapper;
@Resource
private BrandListMapper brandListMapper;
@RequestMapping("/book")
public String getBook() {
return JSON.toJSONString(bookMapper.findAll());
}
@RequestMapping("/brandlist")
public String getBrandList() {
return JSON.toJSONString(brandListMapper.findAll());
}
}
网友评论