自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @ProjectName: gswr-ets-cloud
* @ClassName:
* @Description: 防止重复提交的自定义注解
* @Date: 2022-2-8 9:28
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {
int seconds();
int maxCount();
}
防止重复请求切面
import com.alibaba.fastjson.JSONObject;
import io.renren.commons.tools.utils.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
/**
* @ProjectName: gswr-ets-cloud
* @ClassName:
* @Description: 防止重复请求
* @Date: 2022-2-8 11:12
*/
@Aspect
@Component
public class NoRepeatSubmitAspect {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RedisTemplate redisTemplate;
@Pointcut(@annotation(noRepeatSubmit))
public void pointCut(NoRepeatSubmit noRepeatSubmit) {
}
@Around(pointCut(noRepeatSubmit))
public Result around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {
ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ra.getRequest();
Assert.notNull(request, request can not null);
int seconds = noRepeatSubmit.seconds();
int maxCount = noRepeatSubmit.maxCount();
//获取请求Ip
String ip=request.getRemoteAddr();
//将请求路径及ip组成键值 如:/finance/fastApply/test:192.168.56.1
String key = request.getServletPath() + : + ip ;
//获取请求次数
Integer count = (Integer) redisTemplate.opsForValue().get(key);
if (null == count) {//第一次访问
redisTemplate.opsForValue().set(key, 1,seconds, TimeUnit.SECONDS);
pjp.proceed();
return new Result().ok(第一次请求成功);
}else if (count < maxCount) {//在允许的访问次数内
count = count+1;
redisTemplate.opsForValue().set(key, count,0);
pjp.proceed();
return new Result().ok(请求成功);
}else {//超出访问次数
logger.info(访问过快ip ===> + ip + 且在 + seconds + 秒内超过最大限制 ===> + maxCount + 请求次数达到 ===> + count);
return new Result().error(请求过快);
}
}
}
使用样例
/**
* 测试重复提交 30s内允许请求1次
*/
@NoRepeatSubmit(seconds=30, maxCount=1)
@GetMapping(/test)
public Result test()
{
System.out.println(我被请求了);
return new Result().ok(请求成功);
}
此方法只是简单的根据记录同一IP提交次数去防止重复请求