Spring boot配置多数据源&读AbstractRoutingDataSource源码
引用:https://blog.csdn.net/qq_45515182/article/details/126330084 (直接看Spring AOP + 自定义注解)
下面我们阅读下AbstractRoutingDataSource的源码,逻辑还是挺简单的
AbstractRoutingDataSource
step1:
@Override
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
step2:
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;
}
step3:
determineCurrentLookupKey()子类实现
public static ThreadLocal<String> flag = new ThreadLocal<>();
@Override
protected Object determineCurrentLookupKey() {
return flag.get();
}
resolvedDataSources通过afterPropertiesSet进行赋值
@Override
public void afterPropertiesSet() {
Map<Object,Object> targetDataSource = new ConcurrentHashMap<>();
targetDataSource.put(DataSourceType.MYSQL_DATASOURCE1.name(),mysqlDataSource1);
targetDataSource.put(DataSourceType.MYSQL_DATASOURCE2.name(),mysqlDataSource2);
super.setTargetDataSources(targetDataSource);
super.setDefaultTargetDataSource(mysqlDataSource1);
super.afterPropertiesSet();
}
step4:
resolveSpecifiedLookupKey和resolveSpecifiedDataSource可以忽略
应对一些定制的奇奇怪怪的需求的
@Override
public void afterPropertiesSet() {
if (this.targetDataSources == null) {
throw new IllegalArgumentException("Property 'targetDataSources' is required");
}
this.resolvedDataSources = CollectionUtils.newHashMap(this.targetDataSources.size());
this.targetDataSources.forEach((key, value) -> {
Object lookupKey = resolveSpecifiedLookupKey(key);
DataSource dataSource = resolveSpecifiedDataSource(value);
this.resolvedDataSources.put(lookupKey, dataSource);
});
if (this.defaultTargetDataSource != null) {
this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了