SpringBoot+AOP+自定义注解实现防重复提交

  1. 首先创建自定义注解:主要用来标注在方法上。
import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatCommit {
    //重复提交的方法名
    String methodName();

    //是否开启重复提交检测
    boolean enable() default true;

    //多少秒内算重复提交,默认3s提交多次算重复提交
    int limit() default 3;
}

  1. 创建切面类。
import com.otitan.auth.framework.basepro.common.AuthCommon;
import com.otitan.sd.forest.baseinfo.annotation.RepeatCommit;
import com.otitan.webapp.framework.basepro.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复提交切面类
 */
@Order(2)
@Aspect
@Component
@Slf4j
public class RepeatCommitAspect {
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    AuthCommon authCommon;

    @Pointcut("@annotation(com.otitan.sd.forest.baseinfo.annotation.RepeatCommit)")
    public void pointCut() {

    }

    @Before(value = "pointCut()")
    public void repeatCommitCheck(JoinPoint joinPoint) {
        //获取当前请求的userId
        String userId = authCommon.getLoginUserInfo().getString("id");
        //获取当前注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RepeatCommit repeatCommit = signature.getMethod().getAnnotation(RepeatCommit.class);
        //获取注解每个参数值,用来实现放重复提交逻辑
        boolean enable = repeatCommit.enable();
        if (enable) {
            String methodName = repeatCommit.methodName();
            int limit = repeatCommit.limit();
            String key = userId + methodName;
            if (redisTemplate.opsForValue().get(key) != null) {
                throw new BusinessException("请勿点击过快");
            } else {
                redisTemplate.opsForValue().set(key, userId, limit, TimeUnit.SECONDS);
            }
        }
    }
}

3.controller层方法上直接标注注解
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值