背景及用途
前端页面出现卡顿,用户反复点击操作按钮,导致后台接口短时间内多次提交
实现步骤
设置切面,增加注解,导致在规定时间内该接口不可重复调用
- 设置一个接口
NoRepeatSubmit
import java.lang.annotation.*;
/**
* xzj_2022_8_2
* 重复请求限制切面
*/
@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented //生成文档
public @interface NoRepeatSubmit {
String name() default "name:";
}
- 实现类
import com.alibaba.druid.util.StringUtils;
import com.ipi.organization.constant.CommonKeys;
import com.ipi.organization.service.redis.RedisService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* xzj_2022-8-2
* 接口重复提交拦截切面(两秒内同一客户端不允许重复提交)
*/
@Aspect
@Configuration
public class SubmitAspect {
// redis缓存 可自行更换
@Autowired
public RedisService redisService;
public Logger logger = LoggerFactory.getLogger(getClass());
@Around("execution(public * *(..)) && @annotation(com.xxx.xxx.xxx.NoRepeatSubmit)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
String key = method.getName();
if (!StringUtils.isEmpty(key)) {
if (redisService.get(key) != null) {
return res("请勿重复提交");
}
// redis 设置过期时间
redisService.set(key, "已经存在", 3, TimeUnit.SECONDS);
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("服务器异常");
}
}
/**
* 唯一Key生成
*
* @param method
* @param args
* @return
*/
private String getCacheKey(Method method, Object[] args) {
return method.getName() + args[0];
}
/**
* @param mgs 返回值
*/
private Map<String, Object> res(String mgs) {
Map<String, Object> result = new HashMap<>();
result.put(CommonKeys.MSG, mgs);
result.put(CommonKeys.CODE, "100");
return result;
}
}
- 使用
@GetMapping(value = "/test")
@NoRepeatSubmit
public void test() {
System.out.println("test");
}