Spring动态数据源

1. 多个数据源的配置applicationContext.xml:

<bean id="masterDataSource" parent="parentDataSource">
        <property name="jdbcUrl"  value="${master.jdbc.url}" />
        <property name="username" value="${master.jdbc.username}" />
        <property name="password" value="${master.jdbc.password}" />
    </bean>

    <bean id="slaveDataSource" parent="parentDataSource">
        <property name="jdbcUrl"  value="${slave.jdbc.url}" />
        <property name="username" value="${slave.jdbc.username}" />
        <property name="password" value="${slave.jdbc.password}" />
    </bean>

    <bean id="dataSource" class="com.ivmall.core.datasource.DynamicRoutingDataSource">
       <property name="defaultTargetDataSource" ref="masterDataSource"/>
       <property name="targetDataSources">
          <map key-type="com.ivmall.core.datasource.DynamicDataSource">
             <entry key="MASTER" value-ref="masterDataSource"/>
             <entry key="SLAVE" value-ref="slaveDataSource"/>

          </map>
       </property>
    </bean>

2. DynamicRoutingDataSource类

public class DataSourceContextHolder {
    private static final ThreadLocal<DynamicDataSource> contextHolder =
                new ThreadLocal<DynamicDataSource>();

    public static void setTargetDataSource(DynamicDataSource targetDataSource) {
        Assert.notNull(targetDataSource, "Target data source cannot be null");
        contextHolder.set(targetDataSource);
    }

    public static DynamicDataSource getTargetDataSource() {
        if (contextHolder.get() != null)
            return (DynamicDataSource) contextHolder.get();
        else
            return DynamicDataSource.MASTER;
    }

    public static void resetDefaultDataSource() {
        contextHolder.remove();
    }
}

3.DynamicDataSource类

/**
 * 动态数据源类型
 */
public enum DynamicDataSource {
    MASTER, // 主库(默认)
    SLAVE   // 从库
}


4.serviceImpl中调用,数据库的切换

@Override
    public long countStatUserR(Map<String, Object> map) {
        long r = 0 ;
        try {
            DataSourceContextHolder.setTargetDataSource(DynamicDataSource.SLAVE);//切换到从库
            r =  statUserRDAO.countStatUserR(map);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }finally{
            DataSourceContextHolder.resetDefaultDataSource();//切换回主库
        }
        return r;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值