提交 | 用户 | age
|
826b66
|
1 |
package com.hx.repeat.check; |
C |
2 |
|
|
3 |
import com.hx.common.annotations.repeat.RequestRepeat; |
|
4 |
import com.hx.exception.TipsException; |
|
5 |
import com.hx.redis.RedisUtil; |
|
6 |
import com.hx.util.DateUtil; |
|
7 |
import com.hx.util.IPUtils; |
|
8 |
|
|
9 |
import javax.servlet.http.HttpServletRequest; |
|
10 |
import java.lang.reflect.Method; |
|
11 |
import java.util.Date; |
|
12 |
import java.util.concurrent.TimeUnit; |
|
13 |
|
|
14 |
/** |
|
15 |
* URL防重复提交 |
|
16 |
* @author CJH |
|
17 |
*/ |
|
18 |
public class RequestRepeatUtil { |
|
19 |
|
|
20 |
/**请求重复校验 |
|
21 |
* 目前区分重复是IP地址和请求方法,如果想要更精准,传code |
|
22 |
* @param code 前缀标识,用于区分不同请求来源,长度最好12位之内,可空 |
|
23 |
* @param request HttpServletRequest |
|
24 |
* @param redisUtil redis |
|
25 |
* @param millisecond 间隔时间,毫秒(默认500毫秒) |
|
26 |
* @param annotateCheck 是否注解校验,如果是,将以注解来做校验,否则就全部做校验 |
|
27 |
* @param method 请求方法,方法或者类上面有校验注解,注解跳过或者拦截 |
|
28 |
*/ |
|
29 |
public static void checkRequest(String code,HttpServletRequest request, RedisUtil redisUtil, Long millisecond |
|
30 |
, boolean annotateCheck, Method method){ |
|
31 |
//优先校验注解,优先方法再到类 |
|
32 |
RequestRepeat requestRepeat = method.getAnnotation(RequestRepeat.class); |
|
33 |
if(requestRepeat != null){ |
|
34 |
if(requestRepeat.isRepeat()){ |
|
35 |
check(code,request,redisUtil,requestRepeat.millisecond()); |
|
36 |
}else{ |
|
37 |
return; |
|
38 |
} |
|
39 |
}else{ |
|
40 |
requestRepeat = method.getClass().getAnnotation(RequestRepeat.class); |
|
41 |
if(requestRepeat != null){ |
|
42 |
if(requestRepeat.isRepeat()){ |
|
43 |
check(code,request,redisUtil,requestRepeat.millisecond()); |
|
44 |
}else{ |
|
45 |
return; |
|
46 |
} |
|
47 |
} |
|
48 |
} |
|
49 |
//通过注解校验,不需要全部 |
|
50 |
if(!annotateCheck){ |
|
51 |
check(code,request,redisUtil,millisecond); |
|
52 |
} |
|
53 |
} |
|
54 |
|
|
55 |
public static void check(String code,HttpServletRequest request,RedisUtil redisUtil,Long millisecond){ |
|
56 |
//没有设置,默认0.5秒 |
|
57 |
if(millisecond == null){ |
|
58 |
millisecond = 500L; |
|
59 |
} |
|
60 |
//获取请求的IP地址 |
|
61 |
String ip = IPUtils.getIpAddr(request); |
|
62 |
//获取URL |
|
63 |
String method = request.getServletPath(); |
|
64 |
if(code != null){ |
|
65 |
code = code+"-"+ip+"-"+method; |
|
66 |
}else{ |
|
67 |
code = ip+"-"+method; |
|
68 |
} |
|
69 |
if(!redisUtil.setIfAbsent(code, DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"),millisecond, TimeUnit.MILLISECONDS)){ |
|
70 |
throw new TipsException("请勿频繁操作!"); |
|
71 |
} |
|
72 |
|
|
73 |
} |
|
74 |
|
|
75 |
|
|
76 |
} |