近期开发中,短信接口被不明人士调用,注册的手机号码都无法打通,而且手机号码还不同,因短信平台对同一个手机号码做的有限制,所以公司这边需要做一个针对IP对短信进行限制。
1、先写一个自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Limiter {
/**
* frequency,无法超过frequency次,默认10次
* */
int frequency() default 10;
/**
* 周期时间, 默认30分钟
* */
int duration() default 60;
/**
* 返回的错误信息
* */
String message() default "requests are too frequent";
}
2、接下来通过AOP来对请求进行限制
@Aspect
@Component
public class LimitingAspect {
//redis中存储的key
private static final String LIMITER_KEY = "limit:%s:%s";
private static final String LIMITER_BEGINTIME = "beginTime";
private static final String LIMITER_EXFREQUENCY = "exFrequency";
@Autowired(required = false)
private RedisTemplate redisTemplate;
@Pointcut("@annotation(limiter)")
public void pointcut(Limiter limiter) {
}
@Around("pointcut(limiter)")
public Object around(ProceedingJoinPoint pjp, Limiter limiter) throws Throwable {
//获取请求的ip和访问方法的名称
String ipAddress = WebUtil.getIpAddress();
String methodName = pjp.getSignature().toLongString();
//获取方法的访问周期和频率
long cycle = limiter.duration() * 1000;
int frequency = limiter.frequency();
//获取访问方法的时间
long currentTime = System.currentTimeMillis();
//获取redis中周期内第一次访问方法的时间和执行的次数
Object oBeginTime = redisTemplate.opsForHash().get(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_BEGINTIME);
Long beginTime = 0L;
if (oBeginTime != null) {
beginTime = Long.valueOf(String.valueOf(oBeginTime));
}
Integer exFrequency = 0;
Object oExFrequency = redisTemplate.opsForHash().get(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_EXFREQUENCY);
if (oExFrequency != null) {
exFrequency = Integer.valueOf(String.valueOf(oExFrequency));
}
//如果当前时间减去周期内第一次访问方法的时间大于周几时间,则正常访问
//并将周期被第一次访问方法的时间和执行次数初始化
if (currentTime - beginTime > cycle) {
redisTemplate.opsForHash().put(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_BEGINTIME, String.valueOf(currentTime));
redisTemplate.opsForHash().put(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_EXFREQUENCY, "1");
//设置过期时间
redisTemplate.expire(String.format(LIMITER_KEY, ipAddress, methodName), cycle, TimeUnit.MILLISECONDS);
return pjp.proceed();
} else {
//如果在周期时间内,执行次数小于频率,则正常访问
//并将执行次数加一
if (exFrequency < frequency) {
redisTemplate.opsForHash().increment(String.format(LIMITER_KEY, ipAddress, methodName), LIMITER_EXFREQUENCY, 1);
return pjp.proceed();
} else {
//否则抛出访问频繁异常
throw new FrequentRequestsException(limiter.message());
}
}
}
}
3.获取IP的方法
public class WebUtil {
private static final String UNKNOWN = "unknown";
//获取request
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
//获取response
public static HttpServletResponse getResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
public static String getIpAddress() {
HttpServletRequest request = getRequest();
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
String regex = ",";
if (ip != null && ip.indexOf(regex) > 0) {
ip = ip.split(regex)[0];
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}
但是此方案有个弊端,当一个公司或者小区使用的是一个对外Ip时候,可能会产生问题,所以要设置合理数值
springmvc 中需要在配置文件中加
<aop:aspectj-autoproxy proxy-target-class="true"/>