spring动态设置多数据源

12 篇文章 0 订阅

需求: 项目开发用的sping jdbctemplate, 之前数据源只有一个,现在数据源需要根据需求来进行变更, 也就是说

a用户------>需要访问A数据库服务器

b用户------>需要访问B数据库服务器

查询了资料,发现Spring提供了一个抽象类AbstractRoutingDataSource,为我们很方便的解决了这个问题。

实现:

Spring配置文件applicationContext.xml(包含相关bean类的代码)

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd
    http://cxf.apache.org/jaxrs
    http://cxf.apache.org/schemas/jaxrs.xsd
      
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
               
                 <value>/WEB-INF/jdbc_config.properties</value>
            </list>
        </property>
    </bean> 
    -->
 
    
    <!--  这是原来的写法
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="${jdbc.driverClassName}"/>
      <property name="url" value="${jdbc.url}"/>
      <property name="username" value="${jdbc.username}"/>
      <property name="password" value="${jdbc.password}"/>
    </bean>-->
    
    
    <bean id="serverA" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName"   value="com.mysql.jdbc.Driver"/>
      <property name="url"   value="jdbc:mysql://localhost:3306/test2?useUnicode=true&amp;characterEncoding=utf8" />
      <property name="username"  value="root"/>
      <property name="password"  value="tiger"/>
    </bean>
    
    <bean id="serverB" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName"   value="com.mysql.jdbc.Driver"/>
      <property name="url"   value="jdbc:mysql://112.112.11.132:3306/test?useUnicode=true&amp;characterEncoding=utf8"/>
      <property name="username"   value="root" />
      <property name="password"   value="tiger"/>
    </bean>
    
    
<!-- 这里是重点 -->    
<bean id="dataSource" class="com.rr.datasource.DynamicDataSource">
    <property name="targetDataSources">
        <map key-type="java.lang.String">
            <entry key="server127" value-ref="serverA" />
            <entry key="server112" value-ref="serverB" />
        </map>
    </property>
    <property name="defaultTargetDataSource"  ref="serverA" />
</bean>
    


    <!--注入 spring jdbcTemplate -->
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
           <property name="dataSource" ref="dataSource"/>
   </bean>
    
    <!-- dao -->
    <bean id="initDaoImpl"  class="com.rr.dao.impl.InitDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
    
    <!-- service -->
    <bean id="grantForCompany" class="com.rr.service.GrantForCompany">
        <property name="initDao" ref="initDaoImpl"></property>
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    
    <!-- 事务管理 -->
   <bean id="transctionManager" 
       class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transctionManager"/>
    
    
 </beans>
复制代码

2:  写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法

复制代码
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource 
{
    @Override
    protected Object determineCurrentLookupKey()
    {
        
        return DatabaseContextHolder.getCustomerType();  
    }

}
复制代码

3. 写一个线程安全的ThreadLocal(这个ThreadLocal详细见下篇博客,我之前也没有接触过)

复制代码
public class DatabaseContextHolder
{
    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.当需要切换数据源时,调用一行代码就可以了(也可以用aop自动切换,根据自己需求吧)

DbContextHolder.setDbType("server112"); //server112 就是配置文件中那个targetDataSources的key

targetDataSources是一个map,可以看spring提供的源码.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值