New file |
| | |
| | | package com.hx.repeat.check; |
| | | |
| | | import com.hx.common.annotations.repeat.RequestRepeat; |
| | | import com.hx.exception.TipsException; |
| | | import com.hx.redis.RedisUtil; |
| | | import com.hx.util.DateUtil; |
| | | import com.hx.util.IPUtils; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.lang.reflect.Method; |
| | | import java.util.Date; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * URL防重复提交 |
| | | * @author CJH |
| | | */ |
| | | public class RequestRepeatUtil { |
| | | |
| | | /**请求重复校验 |
| | | * 目前区分重复是IP地址和请求方法,如果想要更精准,传code |
| | | * @param code 前缀标识,用于区分不同请求来源,长度最好12位之内,可空 |
| | | * @param request HttpServletRequest |
| | | * @param redisUtil redis |
| | | * @param millisecond 间隔时间,毫秒(默认500毫秒) |
| | | * @param annotateCheck 是否注解校验,如果是,将以注解来做校验,否则就全部做校验 |
| | | * @param method 请求方法,方法或者类上面有校验注解,注解跳过或者拦截 |
| | | */ |
| | | public static void checkRequest(String code,HttpServletRequest request, RedisUtil redisUtil, Long millisecond |
| | | , boolean annotateCheck, Method method){ |
| | | //优先校验注解,优先方法再到类 |
| | | RequestRepeat requestRepeat = method.getAnnotation(RequestRepeat.class); |
| | | if(requestRepeat != null){ |
| | | if(requestRepeat.isRepeat()){ |
| | | check(code,request,redisUtil,requestRepeat.millisecond()); |
| | | }else{ |
| | | return; |
| | | } |
| | | }else{ |
| | | requestRepeat = method.getClass().getAnnotation(RequestRepeat.class); |
| | | if(requestRepeat != null){ |
| | | if(requestRepeat.isRepeat()){ |
| | | check(code,request,redisUtil,requestRepeat.millisecond()); |
| | | }else{ |
| | | return; |
| | | } |
| | | } |
| | | } |
| | | //通过注解校验,不需要全部 |
| | | if(!annotateCheck){ |
| | | check(code,request,redisUtil,millisecond); |
| | | } |
| | | } |
| | | |
| | | public static void check(String code,HttpServletRequest request,RedisUtil redisUtil,Long millisecond){ |
| | | //没有设置,默认0.5秒 |
| | | if(millisecond == null){ |
| | | millisecond = 500L; |
| | | } |
| | | //获取请求的IP地址 |
| | | String ip = IPUtils.getIpAddr(request); |
| | | //获取URL |
| | | String method = request.getServletPath(); |
| | | if(code != null){ |
| | | code = code+"-"+ip+"-"+method; |
| | | }else{ |
| | | code = ip+"-"+method; |
| | | } |
| | | if(!redisUtil.setIfAbsent(code, DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"),millisecond, TimeUnit.MILLISECONDS)){ |
| | | throw new TipsException("请勿频繁操作!"); |
| | | } |
| | | |
| | | } |
| | | |
| | | |
| | | } |