场景:
springboot项目,默认使用HikariCP连接池 + MybatisPlus持久层框架 + mysql数据库等一套流程,现需求需去第三方sqlserver数据库拉取数据,直连数据库,不走接口,因此,需把项目改造成 多数据源结构,以实现动态切换数据源。
使用docker 安装mysql + sqlserver 数据库 进行测试
实现示例:
0.pom.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <parent> 6 <groupId>com.mumu</groupId> 7 <artifactId>springboot-mumu</artifactId> 8 <version>1.0-SNAPSHOT</version> 9 </parent> 10 <artifactId>mumu-web</artifactId> 11 12 <dependencies> 13 <!-- web --> 14 <dependency> 15 <groupId>org.springframework.boot</groupId> 16 <artifactId>spring-boot-starter-web</artifactId> 17 </dependency> 18 <!-- aop --> 19 <dependency> 20 <groupId>org.springframework.boot</groupId> 21 <artifactId>spring-boot-starter-aop</artifactId> 22 </dependency> 23 <!-- mysql --> 24 <dependency> 25 <groupId>mysql</groupId> 26 <artifactId>mysql-connector-java</artifactId> 27 <scope>runtime</scope> 28 </dependency> 29 <!-- sqlserver --> 30 <dependency> 31 <groupId>com.microsoft.sqlserver</groupId> 32 <artifactId>mssql-jdbc</artifactId> 33 <scope>runtime</scope> 34 </dependency> 35 <!-- mybatis-plus --> 36 <dependency> 37 <groupId>com.baomidou</groupId> 38 <artifactId>mybatis-plus-boot-starter</artifactId> 39 <version>3.0.5</version> 40 </dependency> 41 42 </dependencies> 43 44 <build> 45 <plugins> 46 <plugin> 47 <groupId>org.springframework.boot</groupId> 48 <artifactId>spring-boot-maven-plugin</artifactId> 49 </plugin> 50 </plugins> 51 </build> 52 53 </project>
1.配置文件
server: port: 9587 spring: datasource: hikari: master: driverClassName: com.mysql.cj.jdbc.Driver jdbcUrl: jdbc:mysql://127.0.0.1:3306/d_credit?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 username: root password: 1234567890 slave: driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver jdbcUrl: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=TestDB username: SA password: <1234567890@Passw0rd>
#mybatis-plus
mybatis-plus:
type-aliases-package: com.mumu.model
mapper-locations: classpath:/mapper/**/*.xml
configuration:
jdbc-type-for-null: null
map-underscore-to-camel-case: true
cache-enabled: false
global-config:
db-config:
id-type: auto
field-strategy: not_empty
2.数据源配置类
注意:!!!!!
1.使用mybatis的全局配置文件 这里工厂bean使用SqlSessionFactoryBean
使用mybatis-plus的全局配置 这里工厂bean使用MybatisSqlSessionFactoryBean
否则 mybatis对应的全局配置不会生效
2.@Primary用在DataSourceBuilder.create().build()构建的DataSource方法上,不能放到构建动态数据源方法上,否则会有循环依赖的问题
package com.mumu.common.config;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.mumu.common.datasources.DataSourceNames;
import com.mumu.common.datasources.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.util.HashMap;
import java.util.Map;
/**
* @Description
* @Author Created by Mumu
* @Date on 2019/11/25
*/
@Configuration
@EnableTransactionManagement
@MapperScan("com.mumu.*.mapper")
public class DataSourceConfig {
@Primary
@Bean(name = "master")
@ConfigurationProperties(prefix = "spring.datasource.hikari.master")
public DataSource master() {
return DataSourceBuilder.create().build();
}
@Bean(name = "slave")
@ConfigurationProperties(prefix = "spring.datasource.hikari.slave")
public DataSource slave() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dynamicDataSource")
public DataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map<Object, Object> dataSourceMap = new HashMap<>(2);
dataSourceMap.put(DataSourceNames.FIRST, master());
dataSourceMap.put(DataSourceNames.SECOND, slave());
/// 将 master 数据源作为默认指定的数据源
dynamicDataSource.setDefaultDataSource(master());
// 将 master 和 slave 数据源作为指定的数据源
dynamicDataSource.setDataSources(dataSourceMap);
return dynamicDataSource;
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
// SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 使用mybatis的全局配置文件
//使用mybatisplus的工程bean,mybatis-plus的全局配置文件才会生效
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
// 配置数据源,此处配置为关键配置,如果没有将 dynamicDataSource作为数据源则不能实现切换
sqlSessionFactoryBean.setDataSource(dynamicDataSource());
// 扫描model
sqlSessionFactoryBean.setTypeAliasesPackage("com.mumu.model");
// 扫描映射文件
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:/mapper/**/*Mapper.xml"));
return sqlSessionFactoryBean.getObject();
}
}
3.动态数据源类
我们上一步把这个动态数据源设置到了SQL会话工厂和事务管理器,这样在操作数据库时就会通过动态数据源类来获取要操作的数据源了。
动态数据源类集成了Spring提供的AbstractRoutingDataSource类,AbstractRoutingDataSource 中获取数据源的方法就是 determineTargetDataSource,而此方法又通过 determineCurrentLookupKey 方法获取查询数据源的key。
所以如果我们需要动态切换数据源,就可以通过以下两种方式定制:
1. 覆写 determineCurrentLookupKey 方法
通过覆写 determineCurrentLookupKey 方法,从一个自定义的 DynamicDataSourceContextHolder.getDataSourceKey() 获取数据源key值,这样在我们想动态切换数据源的时候,只要通过 DynamicDataSourceContextHolder.setDataSourceKey(key) 的方式就可以动态改变数据源了。这种方式要求在获取数据源之前,要先初始化各个数据源到 DynamicDataSource 中,我们案例就是采用这种方式实现的,所以在 MybatisConfig 中把master和slave数据源都事先初始化到DynamicDataSource 中。
2. 可以通过覆写 determineTargetDataSource,因为数据源就是在这个方法创建并返回的,所以这种方式就比较自由了,支持到任何你希望的地方读取数据源信息,只要最终返回一个 DataSource 的实现类即可。比如你可以到数据库、本地文件、网络接口等方式读取到数据源信息然后返回相应的数据源对象就可以了。
1 package com.mumu.common.datasources; 2 3 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4 5 import java.util.Map; 6 7 /** 8 * @Description 动态数据源实现类 9 * @Author Created by Mumu 10 * @Date on 2019/11/25 11 */ 12 public class DynamicDataSource extends AbstractRoutingDataSource { 13 /** 14 * 如果希望所有数据源在启动配置时就加载好,这里通过设置数据源Key值来切换数据,定制这个方法 15 */ 16 @Override 17 protected Object determineCurrentLookupKey() { 18 return DynamicDataSourceContextHolder.getDataSourceKey(); 19 } 20 21 /** 22 * 设置默认数据源 23 * @param defaultDataSource 24 */ 25 public void setDefaultDataSource(Object defaultDataSource) { 26 super.setDefaultTargetDataSource(defaultDataSource); 27 } 28 29 /** 30 * 设置数据源 31 * @param dataSources 32 */ 33 public void setDataSources(Map<Object, Object> dataSources) { 34 super.setTargetDataSources(dataSources); 35 // 将数据源的 key 放到数据源上下文的 key 集合中,用于切换时判断数据源是否有效 36 // DynamicDataSourceContextHolder.addDataSourceKeys(dataSources.keySet()); 37 } 38 }
4.动态数据源上下文
动态数据源的切换主要是通过调用这个类的方法来完成的
1 package com.mumu.common.datasources; 2 3 /** 4 * @Description 动态数据源上下文 5 * @Author Created by Mumu 6 * @Date on 2019/11/25 7 */ 8 public class DynamicDataSourceContextHolder { 9 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>() { 10 /** 11 * 将 master 数据源的 key作为默认数据源的 key 12 */ 13 @Override 14 protected String initialValue() { 15 return DataSourceNames.FIRST; 16 } 17 }; 18 19 /** 20 * 获取数据源 21 * @return 22 */ 23 public static String getDataSourceKey() { 24 return contextHolder.get(); 25 } 26 27 /** 28 * 切换数据源 29 * @param key 30 */ 31 public static void setDataSourceKey(String key) { 32 contextHolder.set(key); 33 } 34 35 /** 36 * 重置数据源 37 */ 38 public static void clearDataSourceKey() { 39 contextHolder.remove(); 40 } 41 42 43 }
5.动态数据源注解
1 package com.mumu.common.datasources.annotation; 2 3 import java.lang.annotation.*; 4 5 /** 6 * @Description 动态数据源注解 7 * @Author Created by Mumu 8 * @Date on 2019/11/25 9 */ 10 @Target({ElementType.TYPE, ElementType.METHOD}) 11 @Retention(RetentionPolicy.RUNTIME) 12 @Documented 13 public @interface DataSource { 14 /** 15 * 数据源key值 16 * 17 * @return 18 */ 19 String name() default ""; 20 }
6.动态数据源切换处理器
创建一个AOP切面,拦截带 @DataSource 注解的方法,在方法执行前切换至目标数据源,执行完成后恢复到默认数据源。
1 package com.mumu.common.datasources.aspect; 2 3 import com.mumu.common.datasources.DataSourceNames; 4 import com.mumu.common.datasources.DynamicDataSourceContextHolder; 5 import com.mumu.common.datasources.annotation.DataSource; 6 import lombok.extern.slf4j.Slf4j; 7 import org.aspectj.lang.ProceedingJoinPoint; 8 import org.aspectj.lang.annotation.Around; 9 import org.aspectj.lang.annotation.Aspect; 10 import org.aspectj.lang.annotation.Pointcut; 11 import org.aspectj.lang.reflect.MethodSignature; 12 import org.springframework.core.annotation.Order; 13 import org.springframework.stereotype.Component; 14 15 import java.lang.reflect.Method; 16 17 /** 18 * @Description 动态数据源切换处理器 19 * @Author Created by Mumu 20 * @Date on 2019/11/25 21 */ 22 @Aspect 23 @Component 24 @Slf4j 25 @Order(-1)// 该切面应当先于 @Transactional 执行 26 public class DynamicDataSourceAspect { 27 @Pointcut("@annotation(com.mumu.common.datasources.annotation.DataSource)") 28 public void dataSourcePointCut() { 29 30 } 31 32 @Around("dataSourcePointCut()") 33 public Object around(ProceedingJoinPoint point) throws Throwable { 34 MethodSignature signature = (MethodSignature) point.getSignature(); 35 Method method = signature.getMethod(); 36 37 DataSource ds = method.getAnnotation(DataSource.class); 38 if (ds == null) { 39 DynamicDataSourceContextHolder.setDataSourceKey(DataSourceNames.FIRST); 40 log.info("set datasource is " + DataSourceNames.FIRST); 41 } else { 42 // 切换数据源 43 DynamicDataSourceContextHolder.setDataSourceKey(ds.name()); 44 log.info("Switch DataSource to【{}】in Method【{}】", DynamicDataSourceContextHolder.getDataSourceKey(), signature); 45 } 46 47 try { 48 return point.proceed(); 49 } finally { 50 // 将数据源置为默认数据源 51 DynamicDataSourceContextHolder.clearDataSourceKey(); 52 log.info("Restore DataSource to【{}】in Method【{}】", DynamicDataSourceContextHolder.getDataSourceKey(), signature); 53 } 54 } 55 }
7.测试
默认操作mysql数据源(master),不做特殊处理
1 package com.mumu.service.impl; 2 3 import com.mumu.common.datasources.DataSourceNames; 4 import com.mumu.common.datasources.annotation.DataSource; 5 import com.mumu.model.AddressBook; 6 import com.mumu.persistence.mapper.AddressBookMapper; 7 import com.mumu.service.AddressBookService; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.stereotype.Service; 10 11 /** 12 * @Description 13 * @Author Created by Mumu 14 * @Date on 2019/11/25 15 */ 16 @Service 17 public class AddressBookServiceImpl implements AddressBookService { 18 @Autowired 19 private AddressBookMapper addressBookMapper; 20 21 @Override 22 public AddressBook queryById(Integer bookId){ 23 AddressBook addressBook = addressBookMapper.queryById(bookId); 24 return addressBook; 25 } 26 }
动态切换sqlserver数据源(slave) 通过@DataSource(name = DataSourceNames.SECOND)完成
1 package com.mumu.service.impl; 2 3 import com.mumu.common.datasources.DataSourceNames; 4 import com.mumu.common.datasources.annotation.DataSource; 5 import com.mumu.model.Inventory; 6 import com.mumu.persistence.mapper.InventoryMapper; 7 import com.mumu.service.InventoryService; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.stereotype.Service; 10 11 /** 12 * @Description 13 * @Author Created by Mumu 14 * @Date on 2019/11/25 15 */ 16 @Service 17 public class InventoryServiceImpl implements InventoryService { 18 @Autowired 19 private InventoryMapper inventoryMapper; 20 @Override 21 @DataSource(name = DataSourceNames.SECOND) 22 public Inventory queryById(Integer id){ 23 return inventoryMapper.queryById(id); 24 }; 25 }
8.遇到的问题
多数据源注入、循环依赖问题
自定义sqlSessionFactory时,用错mybatis/mybatis-plus的类,导致对应的mybatis全局配置文件未生效
敬请期待...