Spring aop实现乐观锁重试

如果有错误的地方,大家可以指正出来:

使用:

@TransactionalWithRetries

方法 :{

dto = select  。。

update (dto)

}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TransactionalWithRetries {

    int maxTimes() default 3;

}
@Aspect
@Component
public class RetryOptLockAop {

    private final static Logger log = LoggerFactory.getLogger(RetryOptLockAop.class);

    @Autowired
    TransactionTemplate transactionTemplate;

    @Pointcut("@annotation(TransactionalWithRetries)")
    public void retryOnOptFailure() {
    }

    @Around("retryOnOptFailure()")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        // 参数序列化反序列化,保证不会改变(参数为对象,可能会被方法修改)
        byte[] args = SerializationUtils.serialize(pjp.getArgs());
        TransactionalWithRetries annotation = signature.getMethod().getAnnotation(TransactionalWithRetries.class);
        // 获取注解参数
        int maxTimes = annotation.maxTimes();
        // 没有并发。这样写只是因为lambda表达式里不能直接赋值
        AtomicInteger count = new AtomicInteger(0);
        AtomicReference<Object> result = new AtomicReference<>();
        while (count.get() < maxTimes) {
            try {
                // 事务。如果execut里不抛异常,commit。如果抛异常,会传递出来
                transactionTemplate.execute(status -> {
                    Throwable throwable = null;
                    try {
                        result.set(pjp.proceed((Object[]) SerializationUtils.deserialize(args)));
                    } catch (Throwable t) {
                        throwable = t;
                    }
                    if (throwable != null || !isSuccess(result.get())) {
                        if (throwable == null) {
                            throw new RuntimeException("TransactionalWithRetries OptLock:" + signature.getMethod().getName());
                        } else {
                            throw new RuntimeException(throwable);
                        }
                    } else {
                        // 不再进行重试
                        count.set(maxTimes);
                    }
                    return result.get();
                });
            } catch (Throwable t) {
                count.incrementAndGet();
                log.error("TransactionalWithRetries method:{} args:{} result:{}",
                        signature.getMethod().getName(), SerializationUtils.deserialize(args), result.get(), t);
            }
        }
        return result.get();
    }

    // 方法返回结果为false,或者小于0的数字,也进行重试
    boolean isSuccess(Object obj) {
        if (obj != null) {
            if (obj instanceof Boolean) {
                return (boolean) obj;
            }
            if (obj instanceof Number) {
                if ((int) obj <= 0) {
                    return false;
                }
            }
        }
        return true;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值