关于spring动态切换数据源

本文介绍了如何通过Spring框架实现动态数据源切换,包括创建数据源操作类、动态数据源类及使用AOP通知来切换数据源的具体步骤。此外,还讨论了在切换过程中可能遇到的事务管理问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中有一个需求是要把测试的数据导入到生产环境,导入前要检查生产中是否 有该数据,这就需要多配置一个生产数据源,在查询生产的时候切换过来,不用的时候再切换回来,这就需要用到动态数据源的技术了。

       动态切换数据源的例子网上有很多,我也是参考了很多,按照我的需求从中提取了我需要的东西。但是中间遇到了些问题,最终定位到是和事物有关的(本人对事物理解不是太深,导致搞了好几天才定位到!尴尬

       那么是什么问题呢,就是明明调用了切换数据源的方法但是就是没切换过来!感觉和网上写的一模一样呀!骂人,很头大,然后试了很多办法,比如用AspectJ注解实现aop,以及xml配置aop通知,下面都会介绍到,其实方法都是对的,就是事物配置的问题,下面我们进入正题。

本文中所用的是SSH(spring+springmvc+Hibernate)Mybatis是否管用还没验证!

        1.创建数据源操作类

可以让我们手动设置我们当前想要的数据源(当然我们要用aop去设置,不用手动),sourceDS是我测试库的数据源,shengchanDS是生产数据库的数据源

package com.ecps.ssh.util;

public class DataSourceHolder {
	
	public static final String sourceDS = "sourceDS";
	public static final String shenchanDs = "shengchanDS";
	
	//线程本地环境
	private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
	
	//设置数据源
	public static void setDataSource(String customerType){
		dataSources.set(customerType);
	}
	
	//获取数据源
	public static String getDataSource(){
		return dataSources.get();
	}
	
	//清除数据源
	public static void clearDataSource(){
		dataSources.remove();
	}
	
}
      2.创建动态数据源类

用上面数据源操作类将目前线程中的数据源名字给determineCurrentLookupKey这个方法,它就可以改变数据源的方法

package com.ecps.ssh.util;

import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

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

public class DynamicDataSource extends AbstractRoutingDataSource{

	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

	@Override
	protected Object determineCurrentLookupKey() {
		return DataSourceHolder.getDataSource();
	}

}

    3.注解方式实现aop通知

创建@Aspect注解的aop切面类

要使用@Aspect注解必须在applicationContext.xml中配置

<!-- 支持 @AspectJ 标记-->
<aop:aspectj-autoproxy expose-proxy="true"/>

expos-proxy="true" 是本项目特殊需求必须要的属性,它支持在同一个service直接的方法调用也能触发事物,例如

public class  UserServiceImpl  implements UserService{

public void findA(){

............

       }

     public void queryB(){ 

...........

        this.((UserService)AopContext.currentProxy()).findA();//只有配置了expos-proxy="true"才能这么写,并且触发配置给a方法的切面通知(@Before、@After)

      }

}

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;

@Aspect
@Order(1)
public class AspectJAdvice {
	
	@Before("execution(* com.ecps.ssh.service..*.checkSql(..))")
	public void before(){
		DataSourceHolder.setDataSource(DataSourceHolder.shenchanDs);//调用方法前就设置为生产数据源
	}
	@After("execution(* com.ecps.ssh.service..*.checkSql(..))")
	public void after(){
		DataSourceHolder.clearDataSource();//调用后清除数据源,系统然后就调用默认数据源了
	}
}


4.xml配置的方式实现aop通知

<!-- 支持 @AspectJ 标记-->
	<aop:aspectj-autoproxy expose-proxy="true"/>

	<!-- 以AspectJ方式 定义 AOP execution(* com.wu.service..*.*(..))-->
	<bean id="AopAdvice" class="com.ecps.ssh.util.AopAdvice"/> 
	<aop:config proxy-target-class="true" > 
		<aop:advisor pointcut="execution(* com.ecps.ssh.service..*.*(..))" advice-ref="txAdvice" order="2"/> 
		<aop:aspect ref="aspectJAdvice" order="1">
			<aop:pointcut expression="execution(* com.ecps.ssh.service..*.checkSql(..))" id="shengchanPointCut"/>
			<aop:before method="before" pointcut-ref="shengchanPointCut"/>
			<aop:after method="after" pointcut-ref="shengchanPointCut"/>
		</aop:aspect>
	</aop:config> 
这种方式需要创建通知类,就是上面配置中的AopAdvice类
package com.ecps.ssh.util;

public class AopAdvice {
	public void before(){
		DataSourceHolder.setDataSource(DataSourceHolder.shenchanDs);
		System.out.println("=====切换为生产数据源");
	}
	public void after(){
		DataSourceHolder.clearDataSource();
		System.out.println("=====清除生产数据源");
	}
}

这样就是我们的实现方法,上面的1-2-3  和1-2-4两种都可以


下面讲讲遇到的事物问题

一般的事物配置如下

<tx:advice id="txAdvice">
		<tx:attributes>
			<tx:method name="find*"   read-only="true"   propagation="SUPPORTS" />
			<tx:method name="get*"    read-only="true"   propagation="SUPPORTS" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="add*"    propagation="REQUIRED" />
			<tx:method name="check*"    propagation="REQUIRED" />
			<tx:method name="*"       read-only="false" propagation="REQUIRED" />
		</tx:attributes>
</tx:advice> 

如果我们的queryB方法调用findA方法,queryB方法是对应上面的*,意思就是要开启一个新事物,然后queryB方法再调用findA方法,findA方法发现已经有事物了,那么它就不开启新事物,所以就没有切换成功。

上面只是个例子,要说明的就是,切换数据源是需要一个新的事物!



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值