SpringMVC配置双数据源,一个java项目同时连接两个数据库

数据源在配置文件中的配置




	

	

	
		
			
				classpath:com/resource/config.properties
			
		
	

	
		
		
		
		
		
		
		
	

	
		
		
		
		
		
		
		
	

	
		
			
				
				
			
		
		
		
	

	
		
		
			
				org.hibernate.dialect.MySQLDialect
				org.springframework.orm.hibernate4.SpringSessionContext
				false
				true
				create
			
		
		
			
				com.po
			
		
	

	
		
	

	
		
		
	

	
		
			
			
			
			
			
		
	

	
		
			
			
			
			
		
	

DynamicDataSource.class

 

package com.core;

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

public class DynamicDataSource extends AbstractRoutingDataSource{

	@Override
	protected Object determineCurrentLookupKey() {
		return DatabaseContextHolder.getCustomerType(); 
	}

}

 DatabaseContextHolder.class设置数据源的类

 

 

package com.core;

public class DatabaseContextHolder {

	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();
	}
}

DataSourceInterceptor.class

 

package com.core;

import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;

@Component
public class DataSourceInterceptor {
	//数据源1
	public static final String SOURCE_PLAN = "dataSourceOne;
	//数据源2
        public static final String SOURCE_FUND = dataSourceTwo;	//数据源1
	public static final String SOURCE_PLAN = "dataSourceOne;
	//数据源2
        public static final String SOURCE_FUND = dataSourceTwo;

 

}springMVC数据源

jdbc_driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
dataSourceOne=jdbc:sqlserver://115.29.***.**;DatabaseName=DB_GuiHua

jdbc_username=**jdbc_password=**

dataSourceTwo=jdbc:sqlserver://115.29.***.*;DatabaseName=DB_Fund

 

 

Spring MVC会默认有一个数据源,当需要更换数据源时,要在调用事务之前配置

 

 

DataSourceContextHolder.setDbType(DataSourceType.SOURCE_FUND);//更换数据源
/**
 * @ClassName: DataSourceContextHolder
 * @Description: 数据库切换工具类
 * @author: wzx
 * @date: 2016-07-27 上午10:26:01
 */
public class DataSourceContextHolder {
	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();
	}
}
SpringMVC配置双数据源,一个java项目同时连接两个数据库_第1张图片 关注公众号,我们一起学java

 

 

 

 

 

 

 

你可能感兴趣的:(java)