在spring中配置多个数据源,并实现动态切换

在spring中配置多个数据源,并实现动态切换

朋友遇到的问题,整理好了,我觉得不错,贴出来分享下。

spring中xml文件中的配置:

<bean id="dataSource1"
		class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
		<property name="driverClass"><value>oracle.jdbc.driver.OracleDriver</value></property>

		<property name="jdbcUrl"><value>jdbc:oracle:thin:@127.0.0.1:1521:ORACLE</value></property>
		<property name="user"><value>htctposp</value></property> 
		<property name="password"><value>htctposp</value></property> 
		<property name="minPoolSize"><value>1</value></property> 
		<property name="maxPoolSize"><value>5</value></property> 
		<property name="maxIdleTime"><value>1800</value></property> 
		</bean>
   <bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mysql?characterEncoding=UTF8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1111"></property>
    </bean> 
   
    <bean id="dataSource" class="com.huateng.util.DynamicDataSource">      
         <property name="targetDataSources">   
          <map key-type="java.lang.String">      
                <entry key="dataSource1" value-ref="dataSource1"/>   
                 <entry key="dataSource2" value-ref="dataSource2"/>   
             </map>     
          </property>      
          <property name="defaultTargetDataSource" ref="dataSource1"/>      
   	 </bean>

写两个工具类DbContextHolder和DynamicDataSource,如下:

public class DynamicDataSource extends AbstractRoutingDataSource{

	static Logger log=Logger.getLogger("DynamicDataSource");
	/* (non-Javadoc)
	 * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey()
	 */
	protected Object determineCurrentLookupKey() {
//		DbContextHolder.setDbType("2");
		return DbContextHolder.getDbType();
	}

}
public class DbContextHolder {
	private static final ThreadLocal contextHolder = new ThreadLocal();
	
	public static void setDbType(String dbType){
		contextHolder.set(dbType);
	}
	
	public static String getDbType(){
		return (String)contextHolder.get();
	}
	
	public static void clearDbType(){
		contextHolder.remove();
	}

}

一般在调用service层之前就要切换数据库(一般要在action中),切换数据库的代码:

DbContextHolder.setDbType("dataSource2");

相关推荐