Mysql 读写分离的 Java 实现

先上代码

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSourceKey();
    }
}
public class DataSourceHolder {
    private static final ThreadLocal<String> threadLocal = new ThreadLocal<String>();
    public static String getDataSourceKey() {
        return threadLocal.get();
    }
    public static void setDataSourceKey(String dataSourceKey) {
        threadLocal.set(dataSourceKey);
    }
}
<bean id="dataSource" class="com.wjxie.test.DynamicDataSource">
    <property name="targetDataSources">
        <map key-type="java.lang.String">
            <entry key="master" value-ref="data_source_master" />
            <entry key="slave" value-ref="data_source_slave" />
        </map>
    </property>
    <property name="defaultTargetDataSource" ref="data_source_master" />
</bean>


最后定义切面(Advisor):在 Service 方法执行之前执行:若请求路径为 get/load/select/fetch 什么的,则执行 DataSourceHolder.setDataSourceKey("slave") ,否则执行 DataSourceHolder.setDataSourceKey("master") 。如有特殊需要,可以在方法体内手工指定想要使用的数据源。

AbstractRoutingDataSource 原理:
DynamicDataSource 在 getConnection() 时,会根据其 determineCurrentLookupKey() 返回的结果( "master" 或 "slave" ),去 Spring 配置文件里面查找对应的 targetDataSource 是 "data_source_master" 还是 "data_source_slave" ,然后建立其连接。

猜你喜欢

转载自dsxwjhf.iteye.com/blog/2219258