Spring Dynamic DataSource Routing

參考資料:
spring动态数据源的切换
Spring动态切换数据源
利用AbstractRoutingDataSource实现动态数据源切换 (一、Spring+Hibernate)
DYNAMIC DATASOURCE ROUTING

package tamino.tsai.config;

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

public class DynamicDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {
		return DynamicDataSourceHolder.getDataSourceType();
	}

}

package tamino.tsai.config;

import tamino.tsai.enums.DataSourceType;

public class DynamicDataSourceHolder {
	private static final ThreadLocal<DataSourceType> contextHolder = new ThreadLocal<DataSourceType>();

	// 設置DB類型
	public static void setDataSourceType(DataSourceType dataSourceType) {
		//Assert.notNull(dataSourceType, "DataSourceType cannot be null");
		contextHolder.set(dataSourceType);
	}

	// 獲取DB類型
	public static DataSourceType getDataSourceType() {
		return (DataSourceType) contextHolder.get();
	}

	// 清除DB類型
	public static void clearDataSourceType() {
		contextHolder.remove();
	}
}

package tamino.tsai.enums;

public enum DataSourceType {
	KEYA,
	KEYB
}

	<bean id="baseDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@host1:port:abc" />
		<property name="username" value="username" />
		<property name="password" value="password" />
	</bean>
	
	<bean id="aDataSource" parent="baseDataSource">
		<property name="url" value="jdbc:oracle:thin:@host1:port:abc" />
	</bean>
	<bean id="bDataSource" parent="baseDataSource">
		<property name="url" value="jdbc:oracle:thin:@host2:port:abc" />
	</bean>

	<bean id="dataSource" class="tamino.tsai.config.DynamicDataSource">
		<property name="targetDataSources">
			<map key-type="tamino.tsai.enums.DataSourceType">
				<entry key="KEYA" value-ref="aDataSource"></entry>
				<entry key="KEYB" value-ref="bDataSource"></entry>
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="uatDataSource">
		</property>
	</bean> 
	<bean id="myDao" class="tamino.tsai.dao.impl.MyDaoImpl">
		<property name="dataSource">
			<ref bean="dataSource"/>
		</property>
	</bean>

你可能感兴趣的:(spring,dataSource)