redis 切面拦截 防重复提交

/**
* aop 防止并发请求
*/
@Slf4j
@Aspect
@Component
public class LimitRequestAspect {
@Autowired
RedisHelper redisHelper;

@Around("@annotation(limitRequest)")
public Object around(ProceedingJoinPoint point, LimitRequest limitRequest) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
// 获取token,假设其在Authorization header中
String token = request.getHeader("fleetToken");
//将请求参数的哈希码、请求路径、请求方法作为防止重复提交的键
String key = token + "-" + request.getRequestURI() + "-" + request.getMethod() + "-" + Arrays.hashCode(point.getArgs());
long isSuccess = redisHelper.setnx(key,"0",limitRequest.lockTime());
if (Objects.equals(isSuccess,0L)){
throw new BusinessException("请求太过频繁,请稍后再试");
}
Object result;
try {
result = point.proceed();
} finally {
redisHelper.del(key);
}
return result;
}
}
posted @ 2024-01-22 18:05  能。  阅读(40)  评论(0)    收藏  举报