`
dsxwjhf
  • 浏览: 70866 次
  • 性别: Icon_minigender_1
  • 来自: 安徽
社区版块
存档分类
最新评论

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" ,然后建立其连接。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics