NoSubmitAop.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package com.cyksj.web.aop;
  2. import cn.hutool.extra.servlet.ServletUtil;
  3. import com.cyksj.common.annotation.NoSubmit;
  4. import com.cyksj.common.exception.BusinessRuntimeException;
  5. import com.google.common.cache.Cache;
  6. import org.apache.commons.logging.Log;
  7. import org.apache.commons.logging.LogFactory;
  8. import org.aspectj.lang.ProceedingJoinPoint;
  9. import org.aspectj.lang.annotation.Around;
  10. import org.aspectj.lang.annotation.Aspect;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.web.context.request.RequestContextHolder;
  14. import org.springframework.web.context.request.ServletRequestAttributes;
  15. import javax.servlet.http.HttpServletRequest;
  16. /**
  17. * @author zwhui
  18. * @date 2020/7/16 上午10:55
  19. */
  20. @Aspect
  21. @Component
  22. public class NoSubmitAop {
  23. private Log logger = LogFactory.getLog(getClass());
  24. @Autowired
  25. private Cache<String, Integer> cache;
  26. @Around("execution(* com.cyksj..*.*(..)) && @annotation(nrs)")
  27. public synchronized Object arround(ProceedingJoinPoint pjp, NoSubmit nrs) throws Throwable{
  28. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  29. HttpServletRequest request = attributes.getRequest();
  30. String ipAddr = ServletUtil.getClientIP(request);
  31. String key = ipAddr + "-" + request.getServletPath();
  32. if (cache.getIfPresent(key) == null) {
  33. // 如果缓存中有这个url视为重复提交
  34. cache.put(key, 0);
  35. return pjp.proceed();
  36. } else {
  37. logger.error("重复提交");
  38. throw BusinessRuntimeException.getInstance("Please do not submit repeatedly");
  39. }
  40. }
  41. }