banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

A simple method to switch data sources

It is basically implemented using AbstractRoutingDataSource.

Inherit this class and implement an abstract method

 @Override
    protected Object determineCurrentLookupKey() {
        return name;
    }

The abstract method returns the name of the dataSource to be used. The current name is saved using ThreadLocal.

/**
 * @author dengqn 2019/12/25-11:15
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    public static final ThreadLocal<String> context = new ThreadLocal<>();
    public static final String MAIN_DATA_SOURCE = "mainDataSource";
    public static final String DATA_SOURCE_240 = "dataSource240";

    public static void setDataSource(String type) {
        context.set(type);
    }

    public static String getDataSource() {
        return context.get();
    }

    public static void clearDataSource() {
        context.remove();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return context.get();
    }
}

Then configure multiple dataSources, let it hold (have a map to store), and each dataSource has a different name.

 <bean id="dataSource" class="com.boyasoftware.datasource.DynamicDataSource">
        <property name="defaultTargetDataSource" ref="mainDataSource"/>
        <property name="targetDataSources">
            <map>
                <entry key="mainDataSource" value-ref="mainDataSource"/>
                <entry key="dataSource240" value-ref="dataSource240"/>
            </map>
        </property>
    </bean>

Note that if the name returned by the current ThreadLocal cannot be found, the default DataSource will be used.

Then you can use our custom mutable dataSource, and switching between threads will not affect each other.

When using, just switch directly.

            DynamicDataSource.clearDataSource();
            DynamicDataSource.setDataSource(DynamicDataSource.DATA_SOURCE_240);
            // Need to switch the query business code
            DynamicDataSource.clearDataSource();
            DynamicDataSource.setDataSource(DynamicDataSource.MAIN_DATA_SOURCE);
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.