JAVA-乐观锁更新失败或业务异常后接口重试

最近在阅读《阿里巴巴Java开发手册》时有这么一段内容:

【强制】并发修改同一记录时,避免更新丢失,需要加锁。要么在应用层加锁,要么在缓存加锁,要么在数据库层使用乐观锁,使用version作为更新依据。说明:如果每次访问冲突概率小于20%,推荐使用乐观锁,否则使用悲观锁。乐观锁的重试次数不得小于3次

 那这个重试机制怎么实现呢,大体思路是:

用aop解决问题
1.自定义重试注解及切面
2.在需要重试的接口上加上自定义注解
3.自定义异常
4.更新失败/业务异常 的时候抛出自定义异常
5.切面中定义重试机制

 代码:

1.自定义重试注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 重试注解(异常重试,乐观锁更新失败重试)
 */
@Target(ElementType.METHOD) // 作用到方法上
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedTryAgain {

    /**
     * 重试次数
     * @return
     */
    int tryTimes() default 3;

}

2.在需要重试的service接口上增加注解

 /**
 * 修改用户
 * @return
 */
@NeedTryAgain(tryTimes = 3)
RbacUser update(RbacUserDTO user);

3.自定义异常

import org.springframework.http.HttpStatus;

import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;

/**
 * 自定义重试异常
 */
public class TryAgainException extends RuntimeException {

    private Integer status = INTERNAL_SERVER_ERROR.value();

    public TryAgainException( String msg) {
        super(msg);
    }

    public TryAgainException(HttpStatus status, String msg) {
        super(msg);
        this.status = status.value();
    }

}

4.更新失败抛出自定义异常

...

if(1 != rbacUserMapper.update(rbacUser)){
    // 回滚
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    // 保存失败,抛出重试异常
    throw new TryAgainException("乐观锁导致修改失败");
}

...

5.自定义重试切面及重试机制

import com.gourd.base.annotation.NeedTryAgain;
import com.gourd.base.exception.BadRequestException;
import com.gourd.base.exception.TryAgainException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;

/**
 * 重试切面
 * @author gourd
 */
@Aspect
@Component
@Slf4j
public class TryAgainAspect{

	private int maxRetries;

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

	@Pointcut("@annotation(com.gourd.base.annotation.NeedTryAgain)")
	public void retryOnOptFailure() {
	}

	@Around("retryOnOptFailure()")
	@Transactional(rollbackFor = Exception.class)
	public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
		// 获取拦截的方法名
		MethodSignature msig = (MethodSignature) pjp.getSignature();
		// 返回被织入增加处理目标对象
		Object target = pjp.getTarget();
		// 为了获取注解信息
		Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
		// 获取注解信息
		NeedTryAgain annotation = currentMethod.getAnnotation(NeedTryAgain.class);
		// 设置重试次数
		this.setMaxRetries(annotation.tryTimes());
		// 重试次数
		int numAttempts = 0;
		do {
			numAttempts++;
			try {
				// 再次执行业务代码
				return pjp.proceed();
			} catch (TryAgainException ex) {
				if (numAttempts > maxRetries) {
					// 如果大于 默认的重试机制 次数,我们这回就真正的抛出去了
					throw new BadRequestException(HttpStatus.BAD_REQUEST,"服务内部错误-重试结束");
				}else{
					// 如果 没达到最大的重试次数,将再次执行
					log.info("^0^ === 正在重试====="+numAttempts+"次");
				}
			}
		} while (numAttempts <= this.maxRetries);

		return null;
	}
}

至此重试机制就完成了,如果是JPA或者hibernate,乐观锁保存失败会报异常,同样的try..catch(ObjectOptimisticLockingFailureException)到之后再抛出自定义异常。

你可能感兴趣的:(重试机制)