1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| import huayue.sports.venue.annotation.AvoidRepeatSubmit; import huayue.sports.venue.common.BusinessException; import lombok.extern.slf4j.Slf4j; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import java.util.UUID;
@Aspect @Component @Slf4j public class RepeatSubmitAspect { private static final int REPEAT_SUBMIT_CODE = 507;
@Autowired private RedisDistributedLock redisDistributedLock;
@Pointcut("@annotation(avoidRepeatSubmit)") public void pointCut(AvoidRepeatSubmit avoidRepeatSubmit) { }
@Around(value = "pointCut(avoidRepeatSubmit)", argNames = "pjp,avoidRepeatSubmit") public Object around(ProceedingJoinPoint pjp, AvoidRepeatSubmit avoidRepeatSubmit) throws Throwable {
long lockMillSeconds = avoidRepeatSubmit.lockTime();
HttpServletRequest request = httpServletRequest();
Assert.notNull(request, "request can not null");
String token = request.getParameter("access_token"); String path = request.getServletPath(); String key = getKey(token, path); log.info("key={}", key); String clientId = getClientId(); boolean isSuccess = redisDistributedLock.setLock(key, clientId, lockMillSeconds); Object result; if (isSuccess) { log.info("tryLock success, key = [{}], clientId = [{}]", key, clientId); try { result = pjp.proceed(); } finally { redisDistributedLock.releaseLock(key, clientId); log.info("releaseLock success, key = [{}], clientId = [{}]", key, clientId); } return result; } else { log.info("tryLock fail, key = [{}]", key); throw new BusinessException("重复请求,请稍后再试"); } }
private HttpServletRequest httpServletRequest() { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); assert requestAttributes != null; return requestAttributes.getRequest(); }
private String getKey(String token, String path) { return token + ":" + path; }
private String getClientId() { return UUID.randomUUID().toString(); }
}
|