近期開發中,短信接口被不明人士調用,註冊的手機號碼都無法打通,而且手機號碼還不同,因短信平臺對同一個手機號碼做的有限制,所以公司這邊需要做一個針對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"/>