/** * @Description: 重复请求 * @Author: Nathan Wang * @Date: 2020-6-12 11:30 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface NotDuplicate { long timeout() default 3; }
@Aspect @Component public class NotDuplicateAop { private static final String KEY = "DUPLICATE_METHOD_"; @Autowired private JedisUtils jedisUtils; @Pointcut("@annotation(com.km.config.duplicate.NotDuplicate)") public void duplicate() { } /** * 对方法拦截后进行参数验证 * @param pjp * @return * @throws Throwable */ @Around("duplicate()") public Object duplicate(ProceedingJoinPoint pjp) throws Throwable { MethodSignature msig = (MethodSignature) pjp.getSignature(); Method currentMethod = pjp.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes()); NotDuplicate notDuplicate = currentMethod.getAnnotation(NotDuplicate.class); //拼接签名 StringBuilder sb = new StringBuilder(currentMethod.getName()); Object[] args = pjp.getArgs(); for (Object object : args) { if(object != null){ sb.append(object.getClass().toString()); sb.append(object.toString()); } } String sign = sb.toString(); ValueOperations<String, String> template = jedisUtils.getStringRedisTemplate(); Boolean getLock = template.setIfAbsent(KEY+sign, "1"); if (!getLock){ throw new RuntimeException("该方法正在执行,不能重复请求" + currentMethod.getName()); } jedisUtils.getRedisTemplate().expire(KEY+sign, notDuplicate.timeout(), TimeUnit.SECONDS); return pjp.proceed(); } }