1.背景
一个主库和N个应用库的数据源,并且会同时操作主库和应用库的数据,需要解决以下两个问题:
- 如何动态管理多个数据源以及切换?
- 如何保证多数据源场景下的数据一致性(事务)?
本文主要探讨这两个问题的解决方案,希望能对读者有一定的启发。
2. 数据源切换原理
通过扩展Spring
提供的抽象类AbstractRoutingDataSource
,可以实现切换数据源。其类结构如下图所示:
-
targetDataSources&defaultTargetDataSource
项目上需要使用的所有数据源和默认数据源。
-
resolvedDataSources&resolvedDefaultDataSource
当
Spring
容器创建AbstractRoutingDataSource
对象时,通过调用afterPropertiesSet
复制上述目标数据源。由此可见,一旦数据源实例对象创建完毕,业务无法再添加新的数据源。 -
determineCurrentLookupKey
此方法为抽象方法,通过扩展这个方法来实现数据源的切换。目标数据源的结构为:
Map<Object, DataSource>
其key
为`lookup key。我们来看官方对这个方法的注释:
lookup key
通常是绑定在线程上下文中,根据这个key
去resolvedDataSources
中取出DataSource
。
根据目标数据源的管理方式不同,可以使用基于配置文件和数据库表两种方式。基于配置文件管理方案无法后续添加新的数据源,而基于数据库表方案管理,则更加灵活。
3. 配置文件解决方案
根据上面的分析,我们可以按照下面的步骤去实现:
- 定义
DynamicDataSource
类继承AbstractRoutingDataSource
,重写determineCurrentLookupKey()
方法。 - 配置多个数据源注入
targetDataSources
和defaultTargetDataSource
,通过afterPropertiesSet()
方法将数据源写入resolvedDataSources
和resolvedDefaultDataSource
。 - 调用
AbstractRoutingDataSource
的getConnection()
方法时,determineTargetDataSource()
方法返回DataSource
执行底层的getConnection()
。
其流程如下图所示:
3.1 创建数据源
DynamicDataSource
数据源的注入,目前业界主流实现步骤如下:
-
在配置文件中定义数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driverClassName=com.mysql.jdbc.Driver # 主数据源 spring.datasource.druid.master.url=jdbcUrl spring.datasource.druid.master.username=*** spring.datasource.druid.master.password=*** # 其他数据源 spring.datasource.druid.second.url=jdbcUrl spring.datasource.druid.second.username=*** spring.datasource.druid.second.password=***
-
在代码中配置Bean
@Configuration public class DynamicDataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.druid.master") public DataSource firstDataSource(){ return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.druid.second") public DataSource secondDataSource(){ return DruidDataSourceBuilder.create().build(); } @Bean @Primary public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(5); targetDataSources.put(DataSourceNames.FIRST, firstDataSource); targetDat