有用到redis的setIfAbsent方法、AOP中的before以及自定义注解
不废话,上代码
注解:IgnoreBatchProcess
这个注解的作用是:如果哪个接口不需要做限制就在哪个接口加这个注解
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface IgnoreBatchProcess {
}
切面:BatchProcessAspect(获取ip的工具类自己随便找一个吧,我就不写了;注意execution的值,填自己的包路径)
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
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.concurrent.TimeUnit;
@Aspect
@Component
@Slf4j
public class BatchProcessAspect {
@Autowired
private RedisService redisService;
@Pointcut("execution(* com.server.web.controller.*.*.*(..))")
public void pointcutExpression() {
}
@Pointcut("@annotation(com.server.log.vo.IgnoreBatchProcess)")
public void pointcutAnnotation() {
}
@Before(value = "pointcutExpression() && !pointcutAnnotation()")
public void before(JoinPoint joinPoint) {
// 获取请求信息
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String apiPath = request.getServletPath();
String ipKey = IpAddressUtils.getClientIpAddress(request) + apiPath;
if (judge(ipKey)) {
throw new BusinessException("短时间内提交请求的次数超过限制");
}
}
private boolean judge(String key) {
return !redisService.setIfAbsent(key, "batchProcess", 1l, TimeUnit.SECONDS);
}
}