思路:利用aop实现根据ip限制一个接口在一段时间内的请求次数
实现方式用了redis,直接设置key的过期时间
先来个注解:
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
* 允许访问的次数,默认值MAX_VALUE
*/
int count() default Integer.MAX_VALUE;
/**
* 时间段,单位为毫秒,默认值一分钟
*/
long time() default 60000;
}
接下来是限制逻辑,2种实现方式,hashMap和redis(注释的内容):
import com.annotation.RequestLimit;
import com.core.websocket.WebSocket;
import com.exception.RequestLimitException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Aspect
public class RequestLimitAop {
private static final Logger logger = LoggerFactory.getLogger(RequestLimitAop.class);
@Autowired
private RedisTemplate redisTemplate;
@Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
public void requestLimit(JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {
try {
Object[] args = joinPoint.getArgs();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String ip = WebSocket.getIpAddress(request);
String url = request.getRequestURL().toString();
String key = "req_limit_".concat(url).concat("_").concat(ip);
boolean checkResult = checkWithRedis(limit, key);
if (!checkResult) {
logger.debug("requestLimited," + "[用户ip:{}],[访问地址:{}]超过了限定的次数[{}]次", ip, url, limit.count());
throw new RequestLimitException();
}
} catch (RequestLimitException e) {
throw e;
} catch (Exception e) {
logger.error("RequestLimitAop.requestLimit has some exceptions: ", e);
}
}
/**
* 以redis实现请求记录
*
* @param limit
* @param key
* @return
*/
private boolean checkWithRedis(RequestLimit limit, String key) {
long count = redisTemplate.opsForValue().increment(key, 1);
if (count == 1) {
redisTemplate.expire(key, limit.time(), TimeUnit.MILLISECONDS);
}
if (count > limit.count()) {
return false;
}
return true;
}
}
最后就是controller了:
@RequestMapping(value = "limit")
@RequestLimit(count = 2)
public String requestLimit(HttpServletRequest request) {
return "test";
}
项目里面还需要开启aop的配置:
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"com.aop"})
public class AopConfig {
@Bean
public RequestLimitAop requestLimitAop() {
return new RequestLimitAop();
}
}
RequestLimitException是自定义的一个RuntimeException子类,在controller层需要处理这个异常:
import com.exception.RequestLimitException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice(basePackages = {"com.web.controller"})
public class ExceptionController {
@ExceptionHandler(RequestLimitException.class)
public String requestLimitException(Model model) {
model.addAttribute("errorMsg", "请求过于频繁,超出限制!");
return "error";
}
}