spring 动态数据源配置以及相关问题

项目中要求读写分离,在spring中做到读写分离,很简单的想到在配置文件中设置两个数据源,一个datesource(只写),一个datesourceread(只读)。但是要根据上下文动态切换数据源,还需要增加两个帮助类。

      类1 ContextHolder

主要功能是帮助切换数据源,其中ThreadLocal保证线程中的一致性,不受其他线程影响。

public class ContextHolder {
	public static final String DATA_SOURCE = "dataSource";
	public static final String DATA_SOURCE_READ = "dataSourceRead";
	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();
	}
}

   类2 MyDataSource

自定义数据源,继承AbstractRoutingDataSource,实现determineCurrentLookupKey()方法。

public class MyDataSource extends AbstractRoutingDataSource {

	/* (non-Javadoc)
	 * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey()
	 */
	@Override
	protected Object determineCurrentLookupKey() {
		return ContextHolder.getCustomerType();
	}

}

配置文件中这样配置:

<bean id="abstractDataSource" abstract="true"  
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值