攔截器+redis實現指定服務的次數現在及登錄攔截


指定服務訪問次數限制:

/**
 * @desc:第三方次數限制攔截
 * @Author:li_shuai
 * @date:Create on 2017/11/10 14:44
 */
public class InvokeLimitInterceptor implements HandlerInterceptor {


    private static final Log log = LogFactory.getLog(InvokeLimitInterceptor.class);


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();
        log.info("InvokeLimitInterceptor uri:"+uri);


       String EquipCode = request.getHeader("Equip-Code");
        log.info("InvokeLimitInterceptor EquipCode:"+EquipCode);
        //判斷設備號
        if (StringUtils.isBlank(EquipCode)) {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(RestResponseUtil.err(-4, "請求參數錯誤:未獲取到設備編號")));
            return false;
        }

        //驗證是否登錄
        LoginUserVO vo = (LoginUserVO) request.getSession().getAttribute(BConstants.CURRENT_USER_KEY);
        if(vo == null) {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(RestResponseUtil.err(ServiceErrorCode.LOGIN_EXPIRE.getCode(), "未拿到當前登錄用戶信息!")));
            return false;
        }

        RedisService redisService = (RedisService)SpringContextUtil.getApplicationContext().getBean(com.pohoocredit.profitcard.backend.service.impl.RedisServiceImpl.class);


        //判斷當前uri調用次數是否超過限制
        Integer count = redisService.getValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + vo.getMobile(), uri);
        log.info("uri:"+uri+",EquipCode:"+EquipCode+"InvokeLimitInterceptor count:"+count);
        if(count!=null&&count>=BConstants.INVOKE_URI_LIMIT_COUNT){
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(RestResponseUtil.err(ServiceErrorCode.INVOKE_EXTEND_COUNT_ERROR.getCode(), "當前手機號超過了調用次數限制")));
            return false;
        }

        Integer equipCount = redisService.getValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + EquipCode, uri);
        log.info("uri:"+uri+",EquipCode:"+EquipCode+"InvokeLimitInterceptor equipCount:"+equipCount);

        //是否超過設備號調用現在
        if(equipCount!=null&&equipCount>=BConstants.INVOKE_URI_LIMIT_COUNT){
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(RestResponseUtil.err(ServiceErrorCode.INVOKE_EXTEND_COUNT_ERROR.getCode(), "當前設備超過了調用次數限制")));
            return false;
        }


        
	//手機號次數判斷 不同的uri共用一個mapKey:BConstants.THIRD_INVOKE_URI_KEY+phone
if (count == null) { Boolean flag = redisService.hasKey(BConstants.THIRD_INVOKE_URI_KEY + vo.getMobile()); log.info("uri:"+uri+",EquipCode:"+EquipCode+"InvokeLimitInterceptor flag:"+flag); if (flag!=null&&flag) { redisService.setValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + vo.getMobile(), uri, 1); }else{ redisService.setValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + vo.getMobile(), uri, 1, BConstants.INVOKE_URI_EXPIRE_TIME, TimeUnit.SECONDS); } }else{ //更新uri對應的調用次數 redisService.setValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + vo.getMobile(), uri, ++count); }
	//設備次數 不同的uri共用一個mapKey:BConstants.THIRD_INVOKE_URI_KEY+EquipCode
if (equipCount == null) { Boolean equipflag = redisService.hasKey(BConstants.THIRD_INVOKE_URI_KEY + EquipCode); log.info("uri:"+uri+",EquipCode:"+EquipCode+"InvokeLimitInterceptor equipflag:"+equipflag); //判斷key是否存在 if(equipflag!=null&&equipflag) { redisService.setValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + EquipCode, uri, 1); }else{ redisService.setValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + EquipCode, uri, 1, BConstants.INVOKE_URI_EXPIRE_TIME, TimeUnit.SECONDS); } }else{ //更新uri對應的調用次數 redisService.setValueByHashKey(BConstants.THIRD_INVOKE_URI_KEY + EquipCode, uri, ++equipCount); } return true; }}

登錄攔截器

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final Log log = LogFactory.getLog(LoginInterceptor.class);
    
    @Autowired
    private RedisService redisService;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        String EquipCode = request.getHeader("Equip-Code");
        //log.info("request EquipCode : " + EquipCode + ", session EquipCode : " + _EquipCode);
        if (StringUtils.isBlank(EquipCode)) {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(RestResponseUtil.err(-4, "請求參數錯誤:未獲取到設備編號")));
            return false;
        }
        LoginUserVO vo = (LoginUserVO) request.getSession().getAttribute(BConstants.CURRENT_USER_KEY);
        if (vo == null || StringUtils.isBlank(vo.getMobile())) {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(RestResponseUtil.err(-10, "用戶未登錄,請登錄後重試")));
            return false;
        }
        String _EquipCode = redisService.getValueByKeyStr(BConstants.REDIS_KEY_EQUIP_CODE_PREFIX + vo.getCustId());
        log.info("request EquipCode : " + EquipCode + ", session EquipCode : " + _EquipCode);
        if (StringUtils.isBlank(_EquipCode) || !_EquipCode.equals(EquipCode)) {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(RestResponseUtil.err(-18, "該用戶在其他設備登錄,請確認是否本人操作!")));
            return false;
        }
        return true;
    }
}


註冊攔截器


@Configuration
public class MvcInterceptorConfig extends WebMvcConfigurerAdapter {
    
    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/aa/loginRegister",
                "/aa/getImgCaptcha", "/aa/captcha", );

        registry.addInterceptor(new InvokeLimitInterceptor()).addPathPatterns("/appcontroller/bindCert", "/controller/checkBankAccount", );

        registry.addInterceptor(new FormTokenInterceptor()).addPathPatterns("/xxx/analogCal", "/xx/cashApply");
        
    }
}


發佈了48 篇原創文章 · 獲贊 36 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章