Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Component
- @Aspect
- public class RetryingTransactionAspect implements Ordered {
- private final Logger logger = LoggerFactory.getLogger(RetryingTransactionAspect.class);
- @Inject
- @Named("transactionManager")
- private PlatformTransactionManager transactionManager;
- @Pointcut("execution(public * * (..))")
- private void anyPublicMethod() {
- }
- @Pointcut("execution(@RetryingTransaction * * (..))")
- private void anyRetryingTransactionAnnotatedMethod() {
- }
- @Around("anyPublicMethod() && anyRetryingTransactionAnnotatedMethod()")
- private Object retryOperation(ProceedingJoinPoint joinPoint) throws Throwable {
- Signature signature = joinPoint.getSignature();
- if (!(signature instanceof MethodSignature)) {
- logger.error("unsupported join point signature {}", signature);
- return doNotApply(joinPoint);
- }
- MethodSignature methodSignature = (MethodSignature) signature;
- Method targetMethod = methodSignature.getMethod();
- RetryingTransaction annotation = targetMethod.getAnnotation(RetryingTransaction.class);
- if (annotation == null) {
- logger.error("advised method {} is missing the required annotation of type {}",
- targetMethod,
- RetryingTransaction.class);
- return doNotApply(joinPoint);
- }
- int maxAttempts = annotation.repeatCount();
- int attemptCount = 0;
- List<Class<? extends Throwable>> exceptions = Arrays.asList(annotation.retryFor());
- Throwable failure;
- TransactionStatus currentTransactionStatus = null;
- do {
- attemptCount++;
- logger.debug("try {} of {} retries for {}", attemptCount, maxAttempts, joinPoint);
- try {
- DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
- transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
- currentTransactionStatus = transactionManager.getTransaction(transactionDefinition);
- Object returnValue = joinPoint.proceed();
- transactionManager.commit(currentTransactionStatus);
- return returnValue;
- } catch (Throwable t) {
- if (!exceptions.contains(t.getClass())) {
- throw t;
- }
- if (currentTransactionStatus != null) {
- transactionManager.rollback(currentTransactionStatus);
- }
- failure = t;
- }
- } while (attemptCount < maxAttempts);
- logger.error("max retry attempts reached");
- throw failure;
- }
- public Object doNotApply(ProceedingJoinPoint joinPoint) throws Throwable {
- logger.info("advice will not apply!");
- return joinPoint.proceed();
- }
- public int getOrder() {
- return 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement