Spring应用程序的数据库访问层通过抛出一个ConcurrencyFailureException异常子类来报告并发失败。因此它有两个直接的子类OptimisticLockingFailureException(乐观锁异常), PessimisticLockingFailureException(悲观锁异常)。在大多数应用程序中,这个异常会传播到TransactionInterceptor。这个TransactionInterceptor包装了内部的业务逻辑,并负责管理业务逻辑的事务。在默认情况下,TransactionInterceptor处理unchecked exception,首先保证事务回滚,然后重新抛出异常。然而,因为数据并发失败大多是暂时的,多数应用程序应该重试事务,而不是把异常传播到表示层。
我们可以用一个Spring AOP interceptor自动重试事务3次,才抛出异常:
[code]public class TransactionRetryInterceptor implements MethodInterceptor {
protected int maxRetryCount = 3;
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
public Object invoke(MethodInvocation invocation) throws Throwable {
int retryCount = 0;
while (true)
try {
ReflectiveMethodInvocation inv =
(ReflectiveMethodInvocation) invocation;
MethodInvocation anotherInvocation = inv.invocableClone();
return anotherInvocation.proceed();
} catch (ConcurrencyFailureException e) {
if (retryCount++ > maxRetryCount)
throw e;
else {
continue;
}
}
}
}[/code]
我们可以用一个Spring AOP interceptor自动重试事务3次,才抛出异常:
[code]public class TransactionRetryInterceptor implements MethodInterceptor {
protected int maxRetryCount = 3;
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
public Object invoke(MethodInvocation invocation) throws Throwable {
int retryCount = 0;
while (true)
try {
ReflectiveMethodInvocation inv =
(ReflectiveMethodInvocation) invocation;
MethodInvocation anotherInvocation = inv.invocableClone();
return anotherInvocation.proceed();
} catch (ConcurrencyFailureException e) {
if (retryCount++ > maxRetryCount)
throw e;
else {
continue;
}
}
}
}[/code]