1.需求
一个主库的数据已经不能满足我们生产需求,需要额外的辅助库集成到项目里来获取所需的数据。或是将读写分开为两个库,完成自有的逻辑。
2.实现原理
如同在Springboot中配置一个数据源一样,我们需要一个主数据源,然后再用同样的方法配置另外一个数据源作为辅,两个数据源有各自独立的DataSourceTransactionManager与SqlSessionFactroy。
3.具体的实现
1) pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.datasources
data
0.0.1-SNAPSHOT
jar
data
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
1.5.4.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.2.0
com.alibaba
druid
1.0.18
mysql
mysql-connector-java
org.springframework.boot
spring-boot-maven-plugin
2)application.properties
# 主数据源,默认的
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.filters=stat,wall,log4j
# 更多数据源
custom.datasource.names=ds1,ds2
custom.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
custom.datasource.ds1.url=jdbc:mysql://localhost:3306/test1
custom.datasource.ds1.username=root
custom.datasource.ds1.password=root
custom.datasource.ds1.filters=stat,wall,log4j
3)数据库
数据库test ,表test
CREATE TABLE `test` (
`id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT,
`name` varchar(36) NOT NULL,
`age` int(2) NOT NULL,
`sex` varchar(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
数据库test1,表test
CREATE TABLE `test` (
`id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT,
`name` varchar(36) NOT NULL,
`age` int(2) NOT NULL,
`sex` varchar(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
两个库表没什么区别,只是单纯的分两个库用户测试。
4)配置数据源Master
package com.sorata.custom.datasources;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuratio