Spring 動態資料來源路由-原始碼分析
本文基於Spring 4.1.6 RELEASE原始碼 進行分析。
先看看之前咱們在spring-mybatis.xml檔案中配置的動態資料來源,如下:
<bean id="dataSource" class="com.ricky.codelab.spring.ds.DynamicRoutingDataSource">
<property name="targetDataSources">
<map key-type="com.ricky.codelab.spring.ds.RouteStrategy">
<entry key="slave1" value-ref="slave1DataSource"/>
<entry key="slave2" value-ref="slave2DataSource"/>
</map>
</property>
<!-- 預設目標資料來源為主庫資料來源 -->
<property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean>
DynamicRoutingDataSource 繼承自AbstractRoutingDataSource 類,程式碼如下:
package com.ricky.codelab.spring.ds;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 動態資料來源切換
*
* @author Ricky Fung
* @create 2016-10-18 22:41
*/
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey () {
return DynamicRoutingContextHolder.getRouteStrategy();
}
}
AbstractRoutingDataSource 類的定義,原始碼如下:
package org.springframework.jdbc.datasource.lookup;
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
private Map<Object, Object> targetDataSources;
private Object defaultTargetDataSource;
private boolean lenientFallback = true;
private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
private Map<Object, DataSource> resolvedDataSources;
private DataSource resolvedDefaultDataSource;
}
AbstractRoutingDataSource 實現了InitializingBean介面,Spring容器啟動時會回撥其afterPropertiesSet()方法,AbstractRoutingDataSource afterPropertiesSet()如下:
public void afterPropertiesSet() {
if(this.targetDataSources == null) {
throw new IllegalArgumentException("Property \'targetDataSources\' is required");
} else {
this.resolvedDataSources = new HashMap(this.targetDataSources.size());
Iterator var1 = this.targetDataSources.entrySet().iterator();
while(var1.hasNext()) {
Entry entry = (Entry)var1.next();
Object lookupKey = this.resolveSpecifiedLookupKey(entry.getKey());
DataSource dataSource = this.resolveSpecifiedDataSource(entry.getValue());
this.resolvedDataSources.put(lookupKey, dataSource);
}
if(this.defaultTargetDataSource != null) {
this.resolvedDefaultDataSource = this.resolveSpecifiedDataSource(this.defaultTargetDataSource);
}
}
}
protected DataSource resolveSpecifiedDataSource(Object dataSource) throws IllegalArgumentException {
if(dataSource instanceof DataSource) {
return (DataSource)dataSource;
} else if(dataSource instanceof String) {
return this.dataSourceLookup.getDataSource((String)dataSource);
} else {
throw new IllegalArgumentException("Illegal data source value - only [javax.sql.DataSource] and String supported: " + dataSource);
}
}
這裡主要把在xml中配置的targetDataSources解析到resolvedDataSources,defaultTargetDataSource 賦值到resolvedDefaultDataSource 。
另外,AbstractRoutingDataSource 繼承自AbstractDataSource,而AbstractDataSource 是DataSource的一個子類,如下:
package org.springframework.jdbc.datasource;
public abstract class AbstractDataSource implements DataSource {
protected final Log logger = LogFactory.getLog(this.getClass());
public AbstractDataSource() {
}
}
因此,我們只需要看AbstractRoutingDataSource 的getConnection()方法實現即可,如下:
public Connection getConnection() throws SQLException {
return this.determineTargetDataSource().getConnection();
}
public Connection getConnection(String username, String password) throws SQLException {
return this.determineTargetDataSource().getConnection(username, password);
}
determineTargetDataSource()方法如下:
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = this.determineCurrentLookupKey();
DataSource 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 + "]");
} else {
return dataSource;
}
}
determineTargetDataSource方法決定返回哪個DataSource 物件,它根據determineCurrentLookupKey方法(這個方法正是我們在DynamicRoutingDataSource類中重寫的方法)獲取資料來源的key,然後從 resolvedDataSources中根據key取出DataSource ,如果返回的DataSource 為空,則使用預設的DataSource。