Java秒杀系统7.3 接口限流防刷

1.1分钟限制5次

1.新建AccessKey  ,五秒钟之内只能访问5次。获取reqeust.getRequestURL();判断次数是否是超过5次,如果次数超过5次返回,如果次数没有超过5次则返回访问太频繁。

前端代码:


function getMashaPath() {
    $.ajax({
        url:"/miaosha/path",
        type:"GET",
        data:{
            goodsId:$("#goodsId").val(),
            verifyCode:$("#verifyCode").val()
        },
        success:function(data){
            if(data.code == 0){//地址合法

               console.log("data+"+data.data);
                doMiaosha(data.data)
            }else{
                layer.msg(data.msg);//提示错误信息
                console.log(data.msg);
            }
        },
        error:function(){
            layer.msg("客户端请求有误");
        }
    });
}

controller:

@ResponseBody
    @RequestMapping(value = "/path")
    public   Result  getMiaoshaPath(HttpServletRequest  request, MiaoshaUser  user,
                                            @RequestParam(value = "goodsId") Long  goodsId,
    @RequestParam(value = "verifyCode",defaultValue = "0") Integer verifyCode
    ){
    // 获得访问次数
        StringBuffer requestURL = request.getRequestURL();
     Integer time = redisService.get(AccessKey.key, ""+requestURL, Integer.class);
      if(time==null){
          redisService.set(AccessKey.key,""+requestURL,1);

      }
      else  if(time<5){
          Long incr = redisService.incr(AccessKey.key, "" + requestURL);
          logger.info(" access  inctr"+incr);
      }else {

          logger.info(" times error "+CodeMsg.MIAOSHA_TIMESERROR);
          return Result.error(CodeMsg.MIAOSHA_TIMESERROR);
      }

        logger.info("test");
     user=getMiaoshauser(request);
        if(user.getId()==null){
            return Result.error(CodeMsg.SESSION_ERROR);
        }

      //  Integer aveifyCode = Integer.valueOf(verifyCode);
        logger.info("averifyCode "+verifyCode);
        // 验证码是否正确
        boolean ret=    miaoshaService.chechVerifyCode(user, goodsId,verifyCode);
        if(!ret){
            return  Result.error(CodeMsg.MIAOSHA_VERYCODEERROR);
        }



     logger.info("test2"+user);
        String path = miaoshaService.createMiaoshaPath(user, goodsId);
     return Result.success(path);
    }

2.通用限流 在每个方法上面都可以用--定义拦截器


 
    
    

你可能感兴趣的:(秒杀项目)