MyBatista多数据源动态切换
- 首先建立两个测试库,我这里是mybatis_dynamic_data_base 和 mybatis_dynamic_data_base2,表名分别是:mybatis_data1 和 mybatis_data2,表结构一样在
表中分别添加两条不同的数据,name字段内容分别是xiaoyang和xiaoYang2 - 项目目录结构为:
- SpringBoot整合MyBatis,引入相对应的Maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>com.yang</groupId>
<artifactId>mybatis-dynamic-data-source</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<lombok.version>1.18.6</lombok.version>
<mybatis.version>2.0.0</mybatis.version>
<lombox.version>1.18.6</lombox.version>
<druid.version>1.1.10</druid.version>
</properties>
<dependencies>
<!-- 添加web启动坐标 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加lombok工具坐标 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- 添加springboot 测试坐标 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- 添加lombox 测试坐标 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombox.version}</version>
</dependency>
<!-- 添加mybatis依赖坐标 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- 添加mysql驱动器坐标 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 添加druid数据源坐标 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 添加AOP坐标 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
</project>
4.动态数据源配置
这里使用的数据源为druid,实现数据源之间的切换用@DataSource自定义注解,配置Aop进行切换 application.yml 配置文件。
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 主数据源
spring.datasource.druid.yang-master.jdbc-url=jdbc:mysql://172.0.0.1:3306/mybatis_dynamic_data_base?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
spring.datasource.druid.yang-master.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.druid.yang-master.username=root
spring.datasource.druid.yang-master.password=12345678
#从数据源
spring.datasource.druid.yang-slave.jdbc-url=jdbc:mysql://172.0.0.1:3306/mybatis_dynamic_data_base2?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
spring.datasource.druid.yang-slave.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.druid.yang-slave.username=root
spring.datasource.druid.yang-slave.password=12345678
mybatis.mapper-locations=classpath:mapper/*.xml
- 多数据源配置类
@Configuration
@Component
public class DynamicDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.yang-master")
public DataSource masterDataSource(){
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.yang-slave")
public DataSource slaveDataSource(){
return DataSourceBuilder.create().build();
}
@Bean
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>(1<<1);
targetDataSources.put("yang-master",masterDataSource);
targetDataSources.put("yang-slave", slaveDataSource);
return new DynamicDataSource(masterDataSource, targetDataSources);
}
}
- 动态数据源切换类
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return getDataSource();
}
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
public static String getDataSource() {
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
- 自定义@DataSource注解,在需要切换数据的Dao或者Mapper接口上添加此注解
/**
* @program: mybatis-dynamic-data-source
* @description: 自定义@DataSource注解,在需要切换数据源的Dao添加此注解
* @author: wen.yang
* @create: 2020-04-02 10:22
**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
String name() default "";
}
- Aop切面类配置
/**
* @program: mybatis-dynamic-data-source
* @description: AOP切面类配置
* @author: yang
* @create: 2020-04-02 10:26
**/
@Aspect
@Component
public class DataSourceAspect {
@Pointcut("@annotation(com.yang.annotation.DataSource)")
public void dataSourcePointCut() {
}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
DataSource dataSource = method.getAnnotation(DataSource.class);
if(dataSource == null){
DynamicDataSource.setDataSource("yang-master");
}else {
DynamicDataSource.setDataSource(dataSource.name());
}
try {
return point.proceed();
} finally {
DynamicDataSource.clearDataSource();
}
}
}
- 启动配置注解信息
/**
* @program: mybatis-dynamic-data-source
* @description: 启动类
* @author: yang
* @create: 2020-04-02 10:16
**/
@MapperScan(basePackages = "com.yang.mapper")
@Import({DynamicDataSourceConfig.class})
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class MybatisDynamicDataSourceApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDynamicDataSourceApplication.class, args);
}
}
- User实体类
/**
* @program: mybatis-dynamic-data-source
* @description: User实体类
* @author: yang
* @create: 2020-04-02 10:32
**/
@Data
public class UserModel {
private int id;
private String name;
private int age;
private String sex;
}
- Controller测试类,通过不同url测试主从数据源
/**
* @program: mybatis-dynamic-data-source
* @description: 测试控制层
* @author: yang
* @create: 2020-04-02 10:31
**/
@RestController
@RequestMapping
public class UserController {
/**
* 主数据源标识
*/
private static final String MASTER = "master";
/**
* 从数据源标识
*/
private static final String SLAVE = "slave";
@Autowired(required = false)
private UserMapper userMapper;
@GetMapping("/{name}/list")
public List<UserModel> list(@PathVariable("name") String name) {
if (name.equals(MASTER)) {
return userMapper.queryAllWithMaster(1);
} else if (SLAVE.equalsIgnoreCase(name)) {
return userMapper.queryAllWithSlave(1);
}
return null;
}
}
- 效果图