1. 动态数据源介绍
1.1 业务背景
电商订单项目分正向和逆向两个部分:其中正向数据库记录了订单的基本信息,包括订单基本信息、订单商品信息、优惠卷信息、发票信息、账期信息、结算信息、订单备注信息、收货人信息等;逆向数据库主要包含了商品的退货信息和维修信息。数据量超过500万行就要考虑分库分表和读写分离,那么我们在正向操作和逆向操作的时候,就需要动态的切换到相应的数据库,进行相关的操作。
1.2 解决思路
现在项目的结构设计基本上是基于MVC的,那么数据库的操作集中在dao层完成,主要业务逻辑在service层处理,controller层处理请求。假设在执行dao层代码之前能够将数据源(DataSource)换成我们想要执行操作的数据源,那么这个问题就解决了
1.3 原理图

Spring内置了一个AbstractRoutingDataSource,它可以把多个数据源配置成一个Map,然后,根据不同的key返回不同的数据源。因为AbstractRoutingDataSource也是一个DataSource接口,因此,应用程序可以先设置好key, 访问数据库的代码就可以从AbstractRoutingDataSource拿到对应的一个真实的数据源,从而访问指定的数据库
1.3.1 查看AbstractRoutingDataSource类
/*** Abstract {@link javax.sql.DataSource} implementation that routes {@link#getConnection()}* calls to one of various target DataSources based on a lookup key. Thelatter is usually* (but not necessarily) determined through some thread-bound transactioncontext.** @author Juergen Hoeller* @since 2.0.1* @see #setTargetDataSources* @see #setDefaultTargetDataSource* @see #determineCurrentLookupKey()*///翻译结果如下/*** 抽象 {@link javax.sql.DataSource} 路由 {@link #getConnection ()} 的实现* 根据查找键调用不同的目标数据之一。后者通常是(但不一定) 通过某些线程绑定事务上下文来确定。** @author* @since 2.0。1* @see #setTargetDataSources* @see #setDefaultTargetDataSource* @see #determineCurrentLookupKey ()*/public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {......./*** Specify the map of target DataSources, with the lookup key as key.* The mapped value can either be a corresponding {@linkjavax.sql.DataSource}* instance or a data source name String (to be resolved via a* {@link #setDataSourceLookup DataSourceLookup}).* <p>The key can be of arbitrary type; this class implements the* generic lookup process only. The concrete key representation will* be handled by {@link #resolveSpecifiedLookupKey(Object)} and* {@link #determineCurrentLookupKey()}.*///翻译如下/***指定目标数据源的映射,查找键为键。*映射的值可以是相应的{@link javax.sql.DataSource}*实例或数据源名称字符串(要通过* {@link #setDataSourceLookup DataSourceLookup})。*键可以是任意类型的; 这个类实现了通用查找过程只。 具体的关键表示将由{@link #resolveSpecifiedLookupKey(Object)}和{@link #determineCurrentLookupKey()}。*/public void setTargetDataSources(Map<Object, Object> targetDataSources) {this.targetDataSources = targetDataSources;}....../*** Determine the current lookup key. This will typically be* implemented to check a thread-bound transaction context.* <p>Allows for arbitrary keys. The returned key needs* to match the stored lookup key type, as resolved by the* {@link #resolveSpecifiedLookupKey} method.*///翻译如下/*** 确定当前的查找键。这通常会* 实现以检查线程绑定的事务上下文。* <p> 允许任意键。返回的密钥需要* 与存储的查找密钥类型匹配, 如* {@link #resolveSpecifiedLookupKey} 方法。*/protected abstract Object determineCurrentLookupKey();}
上面源码中还有另外一个核心的方法setTargetDataSources(Map
它是一个abstract类,所以我们使用的话,推荐的方式是创建一个类来继承它并且实现它的determineCurrentLookupKey() 方法,这个方法介绍上面也进行了说明,就是通过这个方法进行数据源的切换
2. 环境准备
2.1 实体类
public class Product {private Integer id;private String name;private Double price;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Double getPrice() {return price;}public void setPrice(Double price) {this.price = price;}@Overridepublic String toString() {return "Product{" +"id=" + id +", name='" + name + '\'' +", price=" + price +'}';}}
2.2 ProductMapper
public interface ProductMapper {@Select("select * from product")public List<Product> findAllProductM();@Select("select * from product")public List<Product> findAllProductS();}
2.3 ProductService
@Servicepublic class ProductService {@Autowiredprivate ProductMapper productMapper;public void findAllProductM(){// 查询MasterList<Product> allProductM = productMapper.findAllProductM();System.out.println(allProductM);}public void findAllProductS(){// 查询SlaveList<Product> allProductS = productMapper.findAllProductS();System.out.println(allProductS);}}
2.4 ProductController
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/findAllProductM")
public String findAllProductM() {
productService.findAllProductM();
return "master";
}
@GetMapping("/findAllProductS")
public String findAllProductS() {
productService.findAllProductS();
return "slave";
}
}
3. 具体实现
3.1 第一步:配置多数据源
1. 首先,我们在application.properties中配置两个数据源
spring.druid.datasource.master.password=root
spring.druid.datasource.master.username=root
spring.druid.datasource.master.jdbcurl=
jdbc:mysql://localhost:3306/product_master?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.druid.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.druid.datasource.slave.password=root
spring.druid.datasource.slave.username=root
spring.druid.datasource.slave.jdbcurl=
jdbc:mysql://localhost:3306/product_slave?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.druid.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver
2. 在SpringBoot的配置代码中,我们初始化两个数据源
@Configuration
public class MyDataSourceConfiguratioin {
Logger logger = LoggerFactory.getLogger(MyDataSourceConfiguratioin.class);
/**
* Master data source.
*/
@Bean("masterDataSource")
@ConfigurationProperties(prefix = "spring.druid.datasource.master")
DataSource masterDataSource() {
logger.info("create master datasource...");
return DataSourceBuilder.create().build();
}
/**
* Slave data source.
*/
@Bean("slaveDataSource")
@ConfigurationProperties(prefix = "spring.druid.datasource.slave")
DataSource slaveDataSource() {
logger.info("create slave datasource...");
return DataSourceBuilder.create().build();
}
}
3.2 第二步:编写RoutingDataSource
我们用Spring内置的RoutingDataSource,把两个真实的数据源代理为一个动态数据源
public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return "masterDataSource"; } }对这个RoutingDataSource ,需要在SpringBoot中配置好并设置为主数据源
@Bean @Primary DataSource primaryDataSource(@Autowired @Qualifier("masterDataSource") DataSource masterDataSource, @Autowired @Qualifier("slaveDataSource") DataSource slaveDataSource ) { logger.info("create routing datasource..."); Map<Object, Object> map = new HashMap<>(); map.put("masterDataSource", masterDataSource); map.put("slaveDataSource", slaveDataSource); RoutingDataSource routing = new RoutingDataSource(); routing.setTargetDataSources(map); routing.setDefaultTargetDataSource(masterDataSource); return routing; }现在, RoutingDataSource 配置好了,但是,路由的选择是写死的,即永远返回”masterDataSource”,
现在问题来了:如何存储动态选择的key以及在哪设置key?
在Servlet的线程模型中,使用ThreadLocal存储key最合适,因此,我们编写一个RoutingDataSourceContext ,来设置并动态存储keypublic class RoutingDataSourceContext { // holds data source key in thread local: static final ThreadLocal<String> threadLocalDataSourceKey = new ThreadLocal<>(); public static String getDataSourceRoutingKey() { String key = threadLocalDataSourceKey.get(); return key == null ? "masterDataSource" : key; } public RoutingDataSourceContext(String key) { threadLocalDataSourceKey.set(key); } public void close() { threadLocalDataSourceKey.remove(); } }然后,修改RoutingDataSource ,获取key的代码如下:
public class RoutingDataSource extends AbstractRoutingDataSource { protected Object determineCurrentLookupKey() { return RoutingDataSourceContext.getDataSourceRoutingKey(); } }这样,在某个地方,例如一个Controller的方法内部,就可以动态设置DataSource的Key:
@GetMapping("/findAllProductM") public String findAllProductM() { String key = "masterDataSource"; RoutingDataSourceContext routingDataSourceContext = new RoutingDataSourceContext(key); productService.findAllProductM(); return "master"; } @GetMapping("/findAllProductS") public String findAllProductS() { String key = "slaveDataSource"; RoutingDataSourceContext routingDataSourceContext = new RoutingDataSourceContext(key); productService.findAllProductS(); return "slave"; }-
3.3 优化
以上代码是可行的,但是,需要读数据库的地方,就需要加上一大段RoutingDataSourceContextctx = …代码,使用起来十分不便。有没有方法可以简化呢?
有!
我们仔细想想,Spring提供的声明式事务管理,就只需要一个@Transactional() 注解,放在某个Java方法上,这个方法就自动具有了事务。
我们也可以编写一个类似的@RoutingWith(“slaveDataSource”) 注解,放到某个Controller的方法上,这个方法内部就自动选择了对应的数据源。
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RoutingWith { String value() default "master"; }编译前需要添加一个Maven依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>切面类:
@Aspect @Component public class RoutingAspect { @Around("@annotation(routingWith)") public Object routingWithDataSource(ProceedingJoinPoint joinPoint, RoutingWith routingWith) throws Throwable { String key = routingWith.value(); RoutingDataSourceContext ctx = new RoutingDataSourceContext(key); return joinPoint.proceed(); } }注意方法的第二个参数RoutingWith是Spring传入的注解实例,我们根据注解的value()获取配置的key。
改造方法:
@RoutingWith("masterDataSource") @GetMapping("/findAllProductM") public String findAllProductM() { /* String key = "masterDataSource"; RoutingDataSourceContext routingDataSourceContext = new RoutingDataSourceContext(key);*/ productService.findAllProductM(); return "lagou"; } @RoutingWith("slaveDataSource") @GetMapping("/findAllProductS") public String findAllProductS() { /*String key = "slaveDataSource"; RoutingDataSourceContext routingDataSourceContext = new RoutingDataSourceContext(key);*/ productService.findAllProductS(); return "lagou"; }到此为止,我们就实现了用注解动态选择数据源的功能
