【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://10.82.81.51:1433;databaseName=standards">  
        </property>  
        <property name="username" value="youguess"></property>  
        <property name="password" value="youguess"></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://10.82.81.52:1433;databaseName=standards">  
        </property>  
        <property name="username" value="youguess"></property>  
        <property name="password" value="youguess"></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);
            }
        }
    }

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值