1. 动态数据源介绍

1.1 业务背景

电商订单项目分正向和逆向两个部分:其中正向数据库记录了订单的基本信息,包括订单基本信息、订单商品信息、优惠卷信息、发票信息、账期信息、结算信息、订单备注信息、收货人信息等;逆向数据库主要包含了商品的退货信息和维修信息。数据量超过500万行就要考虑分库分表和读写分离,那么我们在正向操作和逆向操作的时候,就需要动态的切换到相应的数据库,进行相关的操作。

1.2 解决思路

现在项目的结构设计基本上是基于MVC的,那么数据库的操作集中在dao层完成,主要业务逻辑在service层处理,controller层处理请求。假设在执行dao层代码之前能够将数据源(DataSource)换成我们想要执行操作的数据源,那么这个问题就解决了

1.3 原理图

image.png
Spring内置了一个AbstractRoutingDataSource,它可以把多个数据源配置成一个Map,然后,根据不同的key返回不同的数据源。因为AbstractRoutingDataSource也是一个DataSource接口,因此,应用程序可以先设置好key, 访问数据库的代码就可以从AbstractRoutingDataSource拿到对应的一个真实的数据源,从而访问指定的数据库

1.3.1 查看AbstractRoutingDataSource类

  1. /**
  2. * Abstract {@link javax.sql.DataSource} implementation that routes {@link
  3. #getConnection()}
  4. * calls to one of various target DataSources based on a lookup key. The
  5. latter is usually
  6. * (but not necessarily) determined through some thread-bound transaction
  7. context.
  8. *
  9. * @author Juergen Hoeller
  10. * @since 2.0.1
  11. * @see #setTargetDataSources
  12. * @see #setDefaultTargetDataSource
  13. * @see #determineCurrentLookupKey()
  14. */
  15. //翻译结果如下
  16. /**
  17. * 抽象 {@link javax.sql.DataSource} 路由 {@link #getConnection ()} 的实现
  18. * 根据查找键调用不同的目标数据之一。后者通常是(但不一定) 通过某些线程绑定事务上下文来确定。
  19. *
  20. * @author
  21. * @since 2.0。1
  22. * @see #setTargetDataSources
  23. * @see #setDefaultTargetDataSource
  24. * @see #determineCurrentLookupKey ()
  25. */
  26. public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
  27. .......
  28. /**
  29. * Specify the map of target DataSources, with the lookup key as key.
  30. * The mapped value can either be a corresponding {@link
  31. javax.sql.DataSource}
  32. * instance or a data source name String (to be resolved via a
  33. * {@link #setDataSourceLookup DataSourceLookup}).
  34. * <p>The key can be of arbitrary type; this class implements the
  35. * generic lookup process only. The concrete key representation will
  36. * be handled by {@link #resolveSpecifiedLookupKey(Object)} and
  37. * {@link #determineCurrentLookupKey()}.
  38. */
  39. //翻译如下
  40. /**
  41. *指定目标数据源的映射,查找键为键。
  42. *映射的值可以是相应的{@link javax.sql.DataSource}
  43. *实例或数据源名称字符串(要通过
  44. * {@link #setDataSourceLookup DataSourceLookup})。
  45. *键可以是任意类型的; 这个类实现了通用查找过程只。 具体的关键表示将由{@link #resolveSpecifiedLookupKey(Object)}和{@link #determineCurrentLookupKey()}。
  46. */
  47. public void setTargetDataSources(Map<Object, Object> targetDataSources) {
  48. this.targetDataSources = targetDataSources;
  49. }
  50. ......
  51. /**
  52. * Determine the current lookup key. This will typically be
  53. * implemented to check a thread-bound transaction context.
  54. * <p>Allows for arbitrary keys. The returned key needs
  55. * to match the stored lookup key type, as resolved by the
  56. * {@link #resolveSpecifiedLookupKey} method.
  57. */
  58. //翻译如下
  59. /**
  60. * 确定当前的查找键。这通常会
  61. * 实现以检查线程绑定的事务上下文。
  62. * <p> 允许任意键。返回的密钥需要
  63. * 与存储的查找密钥类型匹配, 如
  64. * {@link #resolveSpecifiedLookupKey} 方法。
  65. */
  66. protected abstract Object determineCurrentLookupKey();
  67. }

上面源码中还有另外一个核心的方法setTargetDataSources(Map targetDataSources) ,它需要一个Map,在方法注释中我们可以得知,这个Map存储的就是我们配置的多个数据源的键值对。我们整理一下这个类切换数据源的运作方式,这个类在连接数据库之前会执行determineCurrentLookupKey()方法,这个方法返回的数据将作为key去targetDataSources中查找相应的值,如果查找到相对应的DataSource,那么就使用此DataSource获取数据库连接

它是一个abstract类,所以我们使用的话,推荐的方式是创建一个类来继承它并且实现它的determineCurrentLookupKey() 方法,这个方法介绍上面也进行了说明,就是通过这个方法进行数据源的切换

2. 环境准备

2.1 实体类

  1. public class Product {
  2. private Integer id;
  3. private String name;
  4. private Double price;
  5. public Integer getId() {
  6. return id;
  7. }
  8. public void setId(Integer id) {
  9. this.id = id;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public Double getPrice() {
  18. return price;
  19. }
  20. public void setPrice(Double price) {
  21. this.price = price;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Product{" +
  26. "id=" + id +
  27. ", name='" + name + '\'' +
  28. ", price=" + price +
  29. '}';
  30. }
  31. }

2.2 ProductMapper

  1. public interface ProductMapper {
  2. @Select("select * from product")
  3. public List<Product> findAllProductM();
  4. @Select("select * from product")
  5. public List<Product> findAllProductS();
  6. }

2.3 ProductService

  1. @Service
  2. public class ProductService {
  3. @Autowired
  4. private ProductMapper productMapper;
  5. public void findAllProductM(){
  6. // 查询Master
  7. List<Product> allProductM = productMapper.findAllProductM();
  8. System.out.println(allProductM);
  9. }
  10. public void findAllProductS(){
  11. // 查询Slave
  12. List<Product> allProductS = productMapper.findAllProductS();
  13. System.out.println(allProductS);
  14. }
  15. }

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

  1. 我们用Spring内置的RoutingDataSource,把两个真实的数据源代理为一个动态数据源

    public class RoutingDataSource extends AbstractRoutingDataSource {
     @Override
     protected Object determineCurrentLookupKey() {
         return "masterDataSource";
     }
    }
    
  2. 对这个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 ,来设置并动态存储key

    public 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();
     }
    }
    
  3. 然后,修改RoutingDataSource ,获取key的代码如下:

    public class RoutingDataSource extends AbstractRoutingDataSource {
     protected Object determineCurrentLookupKey() {
         return RoutingDataSourceContext.getDataSourceRoutingKey();
     }
    }
    
  4. 这样,在某个地方,例如一个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";
    }
    
  5. 到此为止,我们已经成功实现了数据库的动态路由访问。

    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";
    }
    

    到此为止,我们就实现了用注解动态选择数据源的功能