回顾
在spring源码系列11:事务代理对象的执行那一节,得出的结论
事务执行:通过TransactionInterceptor增强器对
目标方法进行环绕增强。
- 调用目标方法前,创建事务。
- 执行目标方法
- 调用目标方法后,提交事务。
TransactionInterceptor
功能增强功能的是实现在父类TransactionAspectSupport
的invokeWithinTransaction
方法
关键代码:
//创建事务
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal = null;
try {
//执行目标方法
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
//异常回滚
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
cleanupTransactionInfo(txInfo);
}
//提交事务
commitTransactionAfterReturning(txInfo);
return retVal;
最近遇到事务方面的问题。在看了源码后,才对这些问题的出现豁然开朗
事务存在的三个问题
假如有这么一个类
@Service
public class TransactionalService {
@Autowired
UserDao userDao;
public String noTransactionalSave(){
System.out.println("非事务方法");
return save1();
}
@Transactional
public String save1(){
User user = new User("主动方事务方法",0);
save2();
userDao.save(user);
return "save1";
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public String save2(){
User user = new User("被事务方法",1);
userDao.save(user);
return "save2";
}
@Transactional
public synchronized String syncSave(){
System.out.println("锁方法");
User user = new User("锁方法",0);
userDao.save(user);
return "锁";
}
}
记得在事务代理的创建那一节说过,不管是方法上,还是类上使用 @Transactional。都会对此类进行代理的创建。
创建代理后,调用目标方法首先调用的是代理的方法。
以CGLB为例,执行链
调用方法-->动态代理类.方法-->MethodInterceptor.intercept方法-->MethodInvocation.proceed执行增强器链-->Adivce.invoke方法-->目标方法
我们再看看MethodInterceptor.intercept()方法
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
Class<?> targetClass = null;
Object target = null;
try {
//是否暴露出代理对象。
if (this.advised.exposeProxy) {
//将代理对象放到事务上下文中。
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// May be null. Get as late as possible to minimize the time we
// "own" the target, in case it comes from a pool...
target = getTarget();
if (target != null) {
targetClass = target.getClass();
}
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
//没事增强,则使用反射调用目标类方法方法
//也就是处理非事务方法
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = methodProxy.invoke(target, argsToUse);
}
else {
//处理事务方法
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
}
retVal = processReturnType(proxy, target, method, retVal);
return retVal;
}
finally {
if (target != null) {
releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
1.同类中非事务方法调事务方法
首先因为有事务注解,所以会生成代理对象。
因为首先调用的是非事务方法,所以chain.isEmpty()
条件成立,走反射执行目标方法。
执行链:
代理类noTransactionalSave()-->MethodInterceptor.intercept方法-->methodProxy.invoke方法--->目标类.noTransactionalSave()-->目标.save1()方法。
我们看出事务方法save1()虽然有事务注解,但是因为其被非事务方法调用。在本次调用链中,没有走事务增强分支,所以导致了事务的失效。
结论:同类中非事务方法调用事务方法,因为执行链不会走事务增强,导致此次调用中事务方法的事务失效。
解决办法:
(1:出现此中业务场景时,可将非事务方法与事务方法抽象到不同的类中。事务方法所在类会创建事务代理,调用事务方法,走事务增强。
(2:看MethodInterceptor.intercept()
中开头有一个if(this.advised.exposeProxy)
的判断,如果为真,就会把事务代理对象放到事务上下文中,我们可以在非事务方法中,使用AopContext.currentProxy()获
取代理对象,强制save1
方法走代理执行。
项目中,我们遇到最多的应该就是事务失效问题,以前总是对事务失效问题模模糊糊,最近看了AOP源码,才对此有了深刻理解。
2.同类中事务方法调用事务方法
同类中事务方法调用事务方法,虽然不会出现事务失效问题。但是却会出现事务传播失效问题。
执行链:
代理方法.save1()--->MethodInterceptor.intercept方法--->methodProxy.invoke方法--->MethodInvocation.proceed执行增强器链-->Adivce.invoke增强方法--->目标方法.save1--->目标方法.save2
可以看出save1是事务方法,会走事务增强,但是save2的调用,是在save1方法增强调用链中,也就是说save2是依靠save1的事务。save2的事务配置,因为没有走Adivce(TransactionInterceptor).invoke
增强方法,他的事务传播属性不会被解析。
结论:同类中事务方法调用事务方法,传播属性失效。
解决办法:同1中解决
3.调用同步事务方法
最近同事就遇到了这个问题呢。他在事务方法上加了synchronized
关键词,让对此方法的调用强制串行化。
- 第一个线程查询数据库,没有对应的实例数据,则创建一个数据
- 第二个线程进入方法查询数据库,有了对应的值,则不用创建。
以此来达到幂等性问题。
想法是好的,但是结果确是有时还是会创建两条。
问题出在哪里呢?
首先:
在动态代理一节讲过,所谓的代理是在内存中生成了新的字节码文件。
在CGLB情况下,TransactionalService
类生成的代理类TransactionalService$$EnhancerBySpringCGLIB$$cdcbf2e8
中的syncSave()
并没有synchronized
修饰的。
public final String syncSave() {
try {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
return var10000 != null ? (String)var10000.intercept(this, CGLIB$syncSave$1$Method, CGLIB$emptyArgs, CGLIB$syncSave$1$Proxy) : super.syncSave();
} catch (Error | RuntimeException var1) {
throw var1;
} catch (Throwable var2) {
throw new UndeclaredThrowableException(var2);
}
}
其次:
再看看TransactionInterceptor
对事务的增强那一段关键代码。事务的增强逻辑是在TransactionInterceptor
中的。
//创建事务
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal = null;
try {
//执行目标方法
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
//异常回滚
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
cleanupTransactionInfo(txInfo);
}
//提交事务
commitTransactionAfterReturning(txInfo);
return retVal;
也就是说:两个线程都阻塞到目标方法上,当第一个线程离开目标方法时,他的调用回到了TransactionInterceptor
中,做提交事务动作。但是此时第二个线程进入目标方法去执行数据库查询操作,但第一个线程的提交事务动作可能为完成,此时数据库中并没有,所以第二个线程也会创建一个实例数据。这样就可能出现创建两条的情况。
可以看出加锁的范围没有包括到整个事务,把synchronized
加到方法上出发点时好的。但是真实的调用确实从代理类开始的,生成的代理类中并没有加synchronized
,结合事务的增强。导致了synchronized
同步的失效。
结论:@Transcational
注解和synchronized
锁一起使用会导致同步失效。加锁的范围没有包括到整个事务
解决办法:既然两个在一起,不能使用锁范围覆盖整个事务。那就创造一个覆盖整个事务的调用。锁方法与事务方法分离到不同的类中,在锁方法中调用事务方法,不就完成了锁范围覆盖整个事务了吗
总结
透过表象看本质。
事务虽然给我带来了方便,但是因为代理类的生成,有一些隐形的调用存在,导致了我们错误的判断了调用链,带来一些错误。
所以看到本质,才能正确的使用。