拦截器+redis实现指定服务的次数现在及登录拦截

来源:互联网 发布:同业 知乎 编辑:程序博客网 时间:2024/06/17 22:09


指定服务访问次数限制:

/** * @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; }}

登录拦截器

@Componentpublic 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;    }}


注册拦截器


@Configurationpublic 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");            }}


阅读全文
0 0
原创粉丝点击