Java 限制前端重复请求

Java 限制前端重复请求

背景及用途

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

实现步骤

设置切面,增加注解,导致在规定时间内该接口不可重复调用

  • 设置一个接口 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");
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值