mybatisplus乐观锁

在实体类的字段上加上@Version注解 

@Version
private Integer version;

配置插件 ,spring boot 注解方式:

@Configuration
@MapperScan("com.dcqc.summarize.mapper")
public class MybatisPlusConfig {
    /**
     * 旧版
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * 新版
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

  • 说明:

  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity 中
  • 仅支持 updateById(id) 与 update(entity, wrapper) 方法
  • 在 update(entity, wrapper) 方法下, wrapper 不能复用!!!

乐观锁在高并发的情况下同一条数据更新可能会失败,需要用到重试,使用spring-retry框架实现重试机制。

启动类上添加@Retryable

@EnableRetry
@SpringBootApplication
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }

}
在方法上添加@Retryable
import com.mail.elegant.service.TestRetryService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalTime;
 
@RestController
public class TestRetryController {
 
    @Override
    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
 public Result ee(@PathVariable("name")String name) throws Exception {
        FrontDatabase frontDatabase=frontDatabaseService.getById(6);
        frontDatabase.setDatasourceName(name);
       Boolean bb= frontDatabaseService.updateById(frontDatabase);
       if(!bb){
           System.out.println(Thread.currentThread()+"更新失败重试");
           throw new Exception("更新失败");
       }
        return bb ? Result.success() : Result.error();
    }
}

说明: 

value:抛出指定异常才会重试
include:和value一样,默认为空,当exclude也为空时,默认所有异常
exclude:指定不处理的异常
maxAttempts:最大重试次数,默认3次
backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。


注意事项
由于是基于AOP实现,所以不支持类里自调用方法

 

你可能感兴趣的:(java,spring,servlet)