【Spring】jdbc

飞翔在天發表於2024-03-09

動態資料來源切換:

https://www.jianshu.com/p/a042ff2ee2ae

實現資料來源切換的功能就是自定義一個類擴充套件AbstractRoutingDataSource抽象類,其實該相當於資料來源DataSourcer的路由中介,可以實現在專案執行時根據相應key值切換到對應的資料來源DataSource上。

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;

    @Override
    public Connection getConnection() throws SQLException {
        return determineTargetDataSource().getConnection();
    }

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

    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;
    }

    protected abstract Object determineCurrentLookupKey();
}
方法裡使用到了determineCurrentLookupKey()方法,它是AbstractRoutingDataSource類的抽象方法,也是實現資料來源切換要擴充套件的方法,該方法的返回值就是專案中所要用的DataSource的key值,拿到該key後就可以在resolvedDataSource中取出對應的DataSource,如果key找不到對應的DataSource就使用預設的資料來源。

相關文章