1.创建自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Limiter {
/**
* 从第一次访问接口的时间到cycle周期时间内,无法超过frequency次
* @return
*/
int frequency() default 5;
/**
* 周期时间,单位ms:
* 默认周期时间为一分钟
*/
long cycle() default 60 * 1000;
/**
* 返回的错误信息
*/
String message() default "请求过于频繁,请1分钟之后再试";
/**
* 到期时间,单位s:
* 如果在cycle周期时间内超过frequency次,则默认1分钟内无法继续访问
*/
long expireTime() default 1 * 60;
}
2.切面实现
@Aspect
@Component
public class LimiterAspect {
@Autowired
private RedisUtil redisUtil;
@Pointcut("@annotation(limiter)")
public void pointcut(Limiter limiter) {}
@Around("pointcut(limiter)")
public Object around(ProceedingJoinPoint pjp, Limiter limiter) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//获取请求的ip和方法
String ipAddress = IPUtil.getIp(request);
String methodName = pjp.getSignature().toLongString();
//获取方法的访问周期和频率
long cycle = limiter.cycle();
int frequency = limiter.frequency();
long currentTime = System.currentTimeMillis();
//获取redis中周期内第一次访问方法的时间和执行的次数
Long beginTimeLong = (Long) redisUtil.hget(String.format(UserConstants.LIMITING_KEY, ipAddress, methodName), UserConstants.LIMITING_BEGINTIME);
Integer exFrequencyLong = (Integer) redisUtil.hget(String.format(UserConstants.LIMITING_KEY, ipAddress, methodName), UserConstants.LIMITING_EXFREQUENCY);
long beginTime = beginTimeLong == null ? 0L : beginTimeLong;
int exFrequency = exFrequencyLong == null ? 0 : exFrequencyLong;
//如果当前时间减去周期内第一次访问方法的时间大于周期时间,则正常访问
//并将周期内第一次访问方法的时间和执行次数初始化
if (currentTime - beginTime > cycle) {
redisUtil.hset(String.format(UserConstants.LIMITING_KEY, ipAddress, methodName), UserConstants.LIMITING_BEGINTIME, currentTime);
redisUtil.hset(String.format(UserConstants.LIMITING_KEY, ipAddress, methodName), UserConstants.LIMITING_EXFREQUENCY, 1);
redisUtil.expire(String.format(UserConstants.LIMITING_KEY, ipAddress, methodName), limiter.expireTime());
return pjp.proceed();
} else {
//如果在周期时间内,执行次数小于频率,则正常访问
//并将执行次数加一
if (exFrequency < frequency) {
redisUtil.hset(String.format(UserConstants.LIMITING_KEY, ipAddress, methodName), UserConstants.LIMITING_EXFREQUENCY, exFrequency + 1);
redisUtil.expire(String.format(UserConstants.LIMITING_KEY, ipAddress, methodName), limiter.expireTime());
return pjp.proceed();
} else {
//否则抛出访问频繁异常
throw new RuntimeException(limiter.message());
}
}
}
}
3.在需要限制的方法上加上注解
//这里我设置的是3,所以登录时,在规定时间内超过3次就会抛出异常 @Limiter(frequency = 3)
@PostMapping(value = "/userLogin")
public Result<Object> toLogin(@RequestBody User loginUser) throws Exception {
String userName = loginUser.getUserName();
String passWord = loginUser.getPassWord();
User user=userMapper.selectUserOne(userName);
if (user == null) {
return Result.error(UserConstants.UNKNOWN_ACCOUNT);
}
if (user.getValid() == 0) {
return Result.error(UserConstants.LOCKED_ACCOUNT);
}
SimpleHash simpleHash = new SimpleHash("MD5", passWord, user.getSalt(), 1024);
log.info("simpleHashPassWord============"+simpleHash.toHex());
if(!simpleHash.toHex().equals(user.getPassWord())){
return Result.error(UserConstants.INCORRECT_CREDENTIALS);
}
// 生成token
String token = JwtUtil.sign(userName, passWord);
redisUtil.set(UserConstants.PREFIX_USER_TOKEN + token, token,UserConstants.TOKEN_EXPIRE_TIME);
JSONObject obj = new JSONObject();
obj.put("token", token);
obj.put("userInfo", user);
return Result.success(obj);
}
4.测试方法显示抛出了异常