【Spring】26、利用Spring的AbstractRoutingDataSource解決多數據源,讀寫分離問題


多數據源問題很常見,例如讀寫分離數據庫配置。

1、首先配置多個datasource

 

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">  
        </property>  
        <property name="url" value="jdbc:jtds:sqlserver://xxx:1433;databaseName=XXX">  
        </property>  
        <property name="username" value="XXX"></property>  
        <property name="password" value="XXX"></property>  
    </bean>  
    <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">  
        </property>  
        <property name="url" value="jdbc:jtds:sqlserver://XXX:1433;databaseName=XXX">  
        </property>  
        <property name="username" value="XXX"></property>  
        <property name="password" value="XXX"></property>  
</bean> 

 

2、寫一個DynamicDataSource類繼承AbstractRoutingDataSource,並實現determineCurrentLookupKey方法

  

package com.standard.core.util;  
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
public class DynamicDataSource extends AbstractRoutingDataSource {  
    @Override  
    protected Object determineCurrentLookupKey() {  
        return CustomerContextHolder.getCustomerType();  
    }  
}  

3、利用ThreadLocal解決線程安全問題

package com.standard.core.util;  
public class CustomerContextHolder {  
    public static final String DATA_SOURCE_A = "dataSource";  
    public static final String DATA_SOURCE_B = "dataSource2";  
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();  
    public static void setCustomerType(String customerType) {  
        contextHolder.set(customerType);  
    }  
    public static String getCustomerType() {  
        return contextHolder.get();  
    }  
    public static void clearCustomerType() {  
        contextHolder.remove();  
    }  
}  

4、數據源配置

<bean id="dynamicDataSource" class="com.standard.core.util.DynamicDataSource" >  
        <property name="targetDataSources">  
            <map key-type="java.lang.String">  
                <entry value-ref="dataSource" key="dataSource"></entry>  
                <entry value-ref="dataSource2" key="dataSource2"></entry>  
            </map>  
        </property>  
        <property name="defaultTargetDataSource" ref="dataSource" >  
        </property>  
    </bean>   

5、利用攔截器,設置每個請求線程的CustomerContextHolder 

public class DatabaseInterceptor implements Interceptor {

    private static final Logger DB_INC_LOG = LoggerFactory.getLogger(DatabaseInterceptor.class);

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        try {
            Method method = methodInvocation.getMethod();
            if (method != null && method.getAnnotation(ReadOnlyDataSource.class) != null) {
                DataSourceProvider.setDataSource(AvailableDataSources.READ);
            }
            return methodInvocation.proceed();
        } finally {
            DataSourceProvider.clearDataSource();
        }
    

6、重寫AbstractRoutingDataSource的方法determineCurrentLookupKey(),切換數據源,切換讀寫

@Override
    protected Object determineCurrentLookupKey() {
        if (System.currentTimeMillis() - RWSplittingClosed_cache_time <= RW_SPLITTING_CLOSED_TIMEOUT) {
            if (RWSplittingClosed_cache) {
                return AvailableDataSources.WRITE;
            }
            return DataSourceProvider.getDataSource();
        }
        Jedis jedis = null;
        try {
            jedis = pingJedis();
            if (jedis == null) {
                return AvailableDataSources.WRITE;
            }
            Boolean masterForced = Boolean.valueOf(jedis.get(Constants.RW_SPLITTING_CLOSED));
            RWSplittingClosed_cache = masterForced;
            RWSplittingClosed_cache_time = System.currentTimeMillis();
            if (masterForced) {
                return AvailableDataSources.WRITE;
            }
            return DataSourceProvider.getDataSource();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AvailableDataSources.WRITE;
        } finally {
            if (jedis != null) {
                pool.returnResource(jedis);
            }
        }
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM