使用AOP处理事务重试

以下摘自<pojo in action>备查. 算是比较有用的东西,以后可能用到.

Using an AOP interceptor to retry transactions
A Spring application can use a custom AOP interceptor to catch the Concurrency-
FailureException and automatically retry the transaction. Here is a custom
Spring AOP interceptor that does this:
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;
}
}
}
}
This class has a maxRetryCount property whose default value is 3. The invoke()
method catches the ConcurrencyFailureException and loops at most maxRetry-
Count times, retrying the transaction. Because proceed() can only be called once,
invoke() clones the MethodInvocation before calling it. The TransactionRetry-
Interceptor is a good example of the power and flexibility of the Spring framework.

Comments are closed.