并发幂等性防抖

并发幂等性防抖_第1张图片

提交数据,以极快的速度点多次,相同的数据,在并发的情况,如果不做处理那么就会产生多次操作或者记录,或者主键重复报错。

为了解决这个问题,先是做了前端防抖,但是前端并不保险,能绕过或者说是网络不好的情况,

后端也是需要做防抖的处理:

1、做切面环绕、上锁、幂等函数

@Slf4j
@Aspect
@Component
public class NoRepeatSubmitAop {
 

    @Autowired
    private RedisService redisService;

//                         com.hieasy.icrm.project.weixin.controller.wxma.miniapp
    @Synchronized
    @Around("execution(* com.hieasy.icrm.project.weixin.controller.*.*.*Ctrl.*(..)) && @annotation(nrs)")
    public Object arround(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) throws Throwable {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String token=request.getHeader("token");
            if(MyStrUtils.isEmpty(token)) return pjp.proceed();
            String key = token+ "-" + request.getServletPath();
//            log.info("开始请求:{}",key);
            if ( !redisService.haskey(key) ) {// 如果缓存中有这个url视为重复提交
                Object o = pjp.proceed();
                redisService.setCacheObject(key, 0, 10, TimeUnit.SECONDS);
//                log.info("正常提交:{},{}",key, MyDateUtil.getNowDateTime());
                return o;
            } else {
                redisService.setCacheObject(key, 0, 10, TimeUnit.SECONDS);//点了同样的URL继续限制,直到2次点击中间间隔超过了限制
                //return R.error(-889,"请勿重复提交或者操作过于频繁!");
//                log.info("限制提交:{},{}",key, MyDateUtil.getNowDateTime());
                throw new BusinessException("请勿重复提交或者操作过于频繁!(间隔10秒,每次点击重新计算)");
            }
    }
 
}

2、注解使用

    @Target(ElementType.METHOD) // 作用到方法上
    @Retention(RetentionPolicy.RUNTIME) // 运行时有效
    public @interface NoRepeatSubmit {
        String name() default "name:";
    }


    @NoRepeatSubmit
    @PostMapping("/goods/save")
    @ApiOperation(value = "商城商品-保存", notes = "此功能新增、修改均可,单处理,多条处理也都可以")
    @ApiOperationSupport(includeParameters = {})
    public JsonResult save(@RequestBody List list) throws Exception {
        Long tenantId=getPresentTenantId();
        int rows=0;
        QueryWrapper wrapper;
        CrmWxMallGoods item;
        for(CrmWxMallGoods goods:list){
            goods.setTenantId(tenantId);
            wrapper=new QueryWrapper();
            wrapper.eq("tenant_id", tenantId);
            wrapper.eq("item_code", goods.getItemCode());
            item= crmWxMallGoodsService.getOne(wrapper);
            if(null!=item){
                goods.setId(item.getId());
                rows+=crmWxMallGoodsService.updateById(goods)?1:0;
            }else{
                rows+=crmWxMallGoodsService.save(goods)?1:0;
            }
        }
        return toJRAjax(rows);
    }

 

你可能感兴趣的:(Java后端,防抖)