spring动态设置多数据源

需求: 项目开发用的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提供的源码.

 

 

参考博客:

 http://blog.sina.com.cn/s/blog_496782b1010100u1.html 详细讲解,大神的文章

http://blog.163.com/wang_hj138%40126/blog/static/140800106201263151242338/

posted @ 2015-03-10 14:24  菟丝子  阅读(808)  评论(0编辑  收藏  举报

============================================================================== 
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员

==============================================================================