SpringBoot配置多数据源
核心技术点
在Spring 2.x 中引入了AbstractRoutingDataSource, 该类充当了DataSource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的DataSource上。
Spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性。而这样的方案就会不同于常见的单一数据实例的方案,这就要程序在运行时根据当时的请求及系统状态来动态的决定将数据存储在哪个数据库实例中,以及从哪个数据库提取数据。
Spring2.x的版本中采用Proxy模式,就是我们在方案中实现一个虚拟的数据源,并且用它来封装数据源选择逻辑,这样就可以有效地将数据源选择逻辑从Client中分离出来。Client提供选择所需的上下文(因为这是Client所知道的),由虚拟的DataSource根据Client提供的上下文来实现数据源的选择。
具体的实现如下
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// TODO
// 重写 determineCurrentLookupKey 方法
}
}
原理:
// AbstractRoutingDataSource 类
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
因此分析到,如果lookupKey 为null则会走默认配置,如果没有所谓的默认配置则会报错,如果指定了数据源,则会加载指定的配置数据源
代码编写
去除默认数据源
/**
* 1.配置数据库事务
* 2.去除JDBC 自动配置数据源
*/
@EnableTransactionManagement
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class KerwinBootsApplication {
public static void main(String[] args) {
SpringApplication.run(KerwinBootsApplication.class, args);
}
}
多数据源配置
// 多数据源配置
# select 库
spring.datasource.select.jdbc-url=jdbc:mysql://127.0.0.1:3306/test1
spring.datasource.select.driverClassName=com.mysql.jdbc.Driver
spring.datasource.select.username=root
spring.datasource.select.password=
# update 库
spring.datasource.update.jdbc-url=jdbc:mysql://127.0.0.1:3306/test2
spring.datasource.update.driverClassName=com.mysql.jdbc.Driver
spring