java设置前端接口不可重复请求

本文介绍了一种防止前端用户重复提交请求的方法,通过使用AOP技术实现了一个接口类,能够有效避免短时间内多次提交请求的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用场景:前端页面出现卡顿,用户反复点击操作按钮,导致后台接口短时间内多次提交

  1. 创建一个接口类
public @interface NoRepeatSubmit {
    String name() default "name:";
}
  1. 通过切面,设置调用该接口的类不可重复提交
/**
 * 接口重复提交拦截切面(两秒内同一客户端不允许重复提交)
 */
@Aspect
@Configuration
public class SubmitAspect {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
            // 最大缓存 100 个
            .maximumSize(100)
            // 设置缓存过期时间为S
            .expireAfterWrite(2, TimeUnit.SECONDS)
            .build();

    @Around("execution(public * *(..)) && @annotation(com.bos.common.NoRepeatSubmit)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Commit form = method.getAnnotation(Commit.class);
        String key = getCacheKey(method, pjp.getArgs());

        if (com.bos.util.StringUtils.isNotNullOrBlank(key)) {
            if (CACHES.getIfPresent(key) != null) {
                ResultData resultData = new ResultData();
                resultData.setMessage("请勿重复提交");
                resultData.setResult("false");
                return resultData;

            }
            // 如果是第一次请求,就将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];
    }
  1. 测试
   /**
     * 定时发送消息模板
     */
    @GetMapping(value = "/sendCondition")
    @NoRepeatSubmit
    public void sendCondition() {
        System.out.println("test");
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值