利用AbstractRoutingDataSource实现动态数据源切换determineCurrentLookupKey方法

首先看下AbstractRoutingDataSource类结构,继承了AbstractDataSource

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean

既然是AbstractDataSource,当然就是javax.sql.DataSource的子类,于是我们自然地回去看它的getConnection方法:

public Connection getConnection() throws SQLException {  
        return determineTargetDataSource().getConnection();  
    }  
  
    public Connection getConnection(String username, String password) throws SQLException {  
        return determineTargetDataSource().getConnection(username, password);  
    }

关键就在determineTargetDataSource()里:

/** 
     * Retrieve the current target DataSource. Determines the 
     * {@link #determineCurrentLookupKey() current lookup key}, performs 
     * a lookup in the {@link #setTargetDataSources targetDataSources} map, 
     * falls back to the specified 
     * {@link #setDefaultTargetDataSource default target DataSource} if necessary. 
     * @see #determineCurrentLookupKey() 
     */  
    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;  
    }

这里用到了我们需要进行实现的抽象方法determineCurrentLookupKey(),该方法返回需要使用的DataSource的key值,然后根据这个key从resolvedDataSources这个map里取出对应的DataSource,如果找不到,则用默认的resolvedDefaultDataSource。

public void afterPropertiesSet() {  
        if (this.targetDataSources == null) {  
            throw new IllegalArgumentException("Property 'targetDataSources' is required");  
        }  
        this.resolvedDataSources = new HashMap<Object, DataSource>(this.targetDataSources.size());  
        for (Map.Entry entry : this.targetDataSources.entrySet()) {  
            Object lookupKey = resolveSpecifiedLookupKey(entry.getKey());  
            DataSource dataSource = resolveSpecifiedDataSource(entry.getValue());  
            this.resolvedDataSources.put(lookupKey, dataSource);  
        }  
        if (this.defaultTargetDataSource != null) {  
            this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);  
        }  
    }

猜你喜欢

转载自blog.csdn.net/wangchaox123/article/details/93711829
今日推荐