import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {
long timeout() default 3000 ;
}
```java
import com.yckt.game.utils.IpUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
public class NoRepeatSubmitAop {
@Autowired
private StringRedisTemplate redisTemplate;
@Around("@annotation(com.yckt.game.utils.NoRepeatSubmit.NoRepeatSubmit)")
public Object around(ProceedingJoinPoint point) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String ip = IpUtils.getIpAddr(request);
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
String className = method.getDeclaringClass().getName();
String name = method.getName();
String ipKey = String.format("%s#%s",className,name);
String requestParam = getAllRequestParam(request);
int hashCode = Math.abs(ipKey.hashCode());
NoRepeatSubmit avoidRepeatableCommit = method.getAnnotation(NoRepeatSubmit.class);
long timeout = avoidRepeatableCommit.timeout();
Long increment = redisTemplate.opsForValue().increment(requestParam+"_"+ip+hashCode, 1);
if (increment==1){
redisTemplate.expire(requestParam+"_"+ip+hashCode, timeout, TimeUnit.MILLISECONDS);
}else {
return LayuiPageInfo.createPageInfoError(0001,"重复提交!");
}
Object object = point.proceed();
return object;
}
private String getAllRequestParam(HttpServletRequest request) {
Map<String, String> res = new HashMap<String, String>();
StringBuffer sb = new StringBuffer();
Enumeration<?> temp = request.getParameterNames();
if (null != temp) {
while (temp.hasMoreElements()) {
String en = (String) temp.nextElement();
String value = request.getParameter(en);
sb.append(en+"="+value+"|");
}
}
return sb.toString();
}
}