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)到之后再抛出自定义异常。

二、使用框架

1、增加spring-retry依赖:

<retry.version>1.2.5.RELEASE</retry.version>

<!--retry-->
<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>${retry.version}</version>
</dependency>

2、在相应的方法上加上注解:

/**
 * 测试重试
 *
 * @Retryable的参数说明: •value:抛出指定异常才会重试
 * •include:和value一样,默认为空,当exclude也为空时,默认所以异常
 * •exclude:指定不处理的异常
 * •maxAttempts:最大重试次数,默认3次
 * •backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;
 * multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试
 */
@Retryable(value = RetryException.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1))
BaseResponse testRetry();

3、在业务异常出抛出指定异常即可,建议抛出框架定义的异常RetryException。

总结

建议大家还是使用框架,有兴趣和能力的小伙伴可以看下源码。但是第一种方式的AOP思想还是要了解的。

 

Java中,乐观锁重试机制通常用于解决多线程并发操作同一数据时可能出现的数据冲突问题。乐观锁是指在进行并发操作时,假设数据不会被其他线程修改,因此不会进行加锁,而是在更新数据时使用版本号(或时间戳)进行标识,以确保数据更新顺序的正确性。 乐观锁重试机制的基本思路是在更新数据时,先读取数据的版本号,然后进行更新操作。如果更新过程中发现版本号已经被其他线程修改,则说明数据已经被其他线程更新,此时需要进行重试操作,即重新读取数据的最新版本号,再进行更新操作。重试操作可以重复执行一定次数,直到数据更新成功或达到最大重试次数为止。 在Java中,乐观锁重试机制通常使用CAS操作(Compare And Swap)进行实现,CAS操作是一种无锁算法,它通过比较内存中的值和预期值是否相等来判断是否需要更新内存中的值,从而避免了使用锁的开销和风险。 下面是一个使用乐观锁重试机制的示例代码: ```java public class OptimisticLockDemo { private int value; private int version; public synchronized void update(int newValue) { int retryCount = 0; while (retryCount < MAX_RETRY_COUNT) { int currentVersion = version; if (compareAndSet(currentVersion, newValue, currentVersion + 1)) { return; } retryCount++; } throw new RuntimeException("Update failed after " + MAX_RETRY_COUNT + " retries."); } private boolean compareAndSet(int expectedVersion, int newValue, int newVersion) { synchronized (this) { if (version == expectedVersion) { value = newValue; version = newVersion; return true; } return false; } } } ``` 在这个示例代码中,我们使用了一个value变量来存储数据,一个version变量来存储版本号。在update方法中,我们使用了一个while循环来进行重试操作,如果重试次数超过了最大重试次数,则抛出异常。在compareAndSet方法中,我们使用了synchronized关键字来保证原子性,通过比较version值和expectedVersion值是否相等来判断是否需要进行更新操作。如果需要更新操作,则使用CAS操作来更新value和version的值。 需要注意的是,乐观锁重试机制并不是万能的,它只适用于并发更新操作比较少、冲突概率较低的情况。如果并发更新操作比较频繁、冲突概率较高,则可能会导致重试次数过多,影响性能。此时,建议使用悲观锁机制来保证数据的一致性。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值