很多时候为了系统的安全性以及负载考虑,我们都会在请求量过高的时候对系统进行限流处理,那么今天我就我自己做过的一个系统里面的限流方案来介绍一下。
1.首先定义一个注解,用于加在需要进行限流的方法上面对方法的请求进行限流
package cn.org.ppdxzz.limit;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* @description: 自定义限流注解
* @author: PeiChen
* @version: 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
* 允许访问的最大次数
*/
int count() default Integer.MAX_VALUE;
/**
* 时间段,单位是毫秒,默认值一分钟
*/
long time() default 60000;
}
2.定义一个限流切面类,去处理限流相应的一些逻辑
package cn.org.ppdxzz.limit;
import cn.org.ppdxzz.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
/**
* @description: 限流切面处理类
* @author: PeiChen
* @version: 1.0
*/
@Slf4j
@Aspect
@Component
public class RequestLimitAspect {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Before("@annotation(limit)")
public void requestLimit(final JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {
try {
Object[] args = joinPoint.getArgs();
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
for (Object arg : args) {
if (arg instanceof HttpServletRequest) {
request = (HttpServletRequest) arg;
break;
}
}
String ip = IpUtils.getIpAddress(request);
String url = request.getRequestURL().toString();
String key = "limit_".concat(url).concat(ip);
if (!redisTemplate.hasKey(key)) {
redisTemplate.opsForValue().set(key,String.valueOf(1));
} else {
Integer getValue = Integer.parseInt(redisTemplate.opsForValue().get(key)) + 1;
redisTemplate.opsForValue().set(key,String.valueOf(getValue));
}
redisTemplate.expire(key,limit.time(),TimeUnit.MILLISECONDS);
int count = Integer.parseInt(redisTemplate.opsForValue().get(key));
if (count == 1) {
//创建一个定时器
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
redisTemplate.delete(key);
}
};
//这个定时器设定在time规定的时间之后会执行上面的remove方法,也就是说在这个时间后它可以重新访问
new Timer().schedule(timerTask, limit.time());
}
if (count > limit.count()) {
log.info("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
throw new RequestLimitException();
}
} catch (RequestLimitException e) {
throw e;
} catch (Exception e) {
log.error("系统异常,限流中...", e);
}
}
}
3.开发一个限流异常处理类,用于处理系统开始限流的请求
package cn.org.ppdxzz.limit;
/**
* @description: 自定义限流异常类
* @author: PeiChen
* @version: 1.0
*/
public class RequestLimitException extends RuntimeException {
private static final long serialVersionUID = 1L;
public RequestLimitException() {
super("接口请求过于频繁,请稍后再试");
}
public RequestLimitException(String message) {
super(message);
}
}
4.使用限流注解,直接在所需要限流的方法上面加上限流注解
@RequestLimit(count = 5)//代表一分钟最多请求5次,超出则限流