乐观锁更新失败重试解决方案

思路用aop解决问题

1.自定义异常

2 更新失败的时候抛出此异常

3.重试机制



@Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {
    // marker annotation
}

@Aspect
public class ConcurrentOperationExecutor implements Ordered
{

    private static final Logger logger = LoggerFactory.getLogger(ConcurrentOperationExecutor.class);

    private static final int DEFAULT_MAX_RETRIES = 1;

    private int maxRetries = DEFAULT_MAX_RETRIES;
    private int order = 100;

    public void setMaxRetries(int maxRetries)
    {
        this.maxRetries = maxRetries;
    }

    public int getOrder()
    {
        return this.order;
    }

    public void setOrder(int order)
    {
        this.order = order;
    }

    @Around("@annotation(Idempotent)")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable
    {
        int numAttempts = 0;
        OptimisticLockingFailureException lockFailureException;
        do
        {
            numAttempts++;
            try
            {
                return pjp.proceed();
            }
            catch (OptimisticLockingFailureException ex)
            {
                lockFailureException = ex;
                logger.debug("caught lock failure exception, attempts: " + numAttempts);
            }
        }
        while (numAttempts <= this.maxRetries);
        throw lockFailureException;
    }

}

你可能感兴趣的:(乐观锁更新失败重试解决方案)