多数据源配置

jdbc.properties:

首先在jdbc文件中配置多个数据源信息

jdbc.driverClassName=com.mysql.jdbc.Driver
orcl.jdbc.driverClassName=oracle.jdbc.driver.OracleDriver

#生产环境数据库配置
jdbc.url=jdbc:mysql://XXXX:3306/XXX?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
jdbc.username=XXX
jdbc.password=XXX


cpool.checkoutTimeout=1000
cpool.minPoolSize=2
cpool.maxPoolSize=10
cpool.maxIdleTime=300
cpool.maxIdleTimeExcessConnections=100
cpool.acquireIncrement=2



#XX数据库配置
zg1.jdbc.url=jdbc\:oracle\:thin\:@XXX\:1522\:orcl
zg1.jdbc.username=XXX
zg1.jdbc.password=XXX

applicationContext.xml

编写DynamicDataSource.java类

并在applicationContext文件中进行动态配置


	
		
		
		
		
		
		
		
		
		
		
		
		
	
	
	
	
		
		
		
		
		
		
		
		
		
		
		
		
	 



		
		
			
				
				
			
		
	
	


	
		
	
	
	
	
	
	
		
		
		
		
	
	
	
	
	
		
		
	
	

DynamicDataSource.java

package com.run.XXX.util;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource{

	
	public static final String defultDataSource= "default_dataSource";
	public static final String zg1DataSource= "zg1_dataSource";
	
	private static final ThreadLocal contextHolder = new ThreadLocal();
	
	
	public static void setCustomerType(String customerType){
		contextHolder.set(customerType);
	}
	
	public static String getCustomerType(){
		return contextHolder.get();
	}
	
	public static void clearCustomerType(){
		contextHolder.remove();
	}
	
	
	@Override
	protected Object determineCurrentLookupKey() {
		return getCustomerType();
	}

}

 

数据源切换使用:

//切库
			DynamicDataSource.clearCustomerType();
			DynamicDataSource.setCustomerType(DynamicDataSource.zg1DataSource);
			
				XXXDao.insert(XXX);
			
//恢复为默认库
			DynamicDataSource.clearCustomerType();
			DynamicDataSource.setCustomerType(DynamicDataSource.defultDataSource);

 

 

 

你可能感兴趣的:(javaWeb,多数据源)