spring動態設置多數據源

需求: 項目開發用的sping jdbctemplate, 以前數據源只有一個,如今數據源須要根據需求來進行變動, 也就是說html

a用戶------>須要訪問A數據庫服務器java

b用戶------>須要訪問B數據庫服務器mysql

查詢了資料,發現Spring提供了一個抽象類AbstractRoutingDataSource,爲咱們很方便的解決了這個問題。spring

實現:sql

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方法apache

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 app

targetDataSources是一個map,能夠看spring提供的源碼.

 

 

參考博客:

 http://blog.sina.com.cn/s/blog_496782b1010100u1.html 詳細講解,大神的文章

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

相關文章
相關標籤/搜索