1,在pom.xml文件中引入缓存的jar包
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency>
2,自定义一个注解类,将来用在禁止重复提交的方法上
public @interface FormCommit { String name() default "name:"; }
3,自定义一个切面类,利用aspect实现切入所有方法
@Aspect @Configuration public class SubmitAspect { private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder() // 最大缓存 100 个 .maximumSize(100) // 设置缓存过期时间为S .expireAfterWrite(3, TimeUnit.SECONDS) .build(); @Around("execution(public * *(..)) && @annotation(com.ding.web.FormCommit)") public Object interceptor(ProceedingJoinPoint pjp) { MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); FormCommit form= method.getAnnotation(FormCommit.class); String key = getCacheKey(method, pjp.getArgs()); if (!StringUtils.isEmpty(key)) { if (CACHES.getIfPresent(key) != null) { ResultResponse resultResponse = new ResultResponse(); resultResponse.setData(null); resultResponse.setMsg("请勿重复请求"); resultResponse.setCode(405); return resultResponse; } // 如果是第一次请求,就将key存入缓存中 CACHES.put(key, key); } try { return pjp.proceed(); } catch (Throwable throwable) { throw new RuntimeException("服务器异常"); } finally { CACHES.invalidate(key); } } /** *将来还要加上用户的唯一标识 */ private String getCacheKey(Method method Object[] args) { return method.getName() + args[0]; } }
4,在禁止提交的方法上加上注解@FormCommit