springboot 使用注解进行重复提交校验

使用注解,对特定接口进行重复数据的校验

@RepeatSubmit


import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;

/**
 * @Author 
 * @Description
 * @Date create in 2023-12-26 11:21
 */
@Retention(RetentionPolicy.RUNTIME)//运行时生效
@Target(ElementType.METHOD)//作用在方法上
public @interface RepeatSubmit {
    /**
     * key的前缀,默认取方法全限定名,除非我们在不同方法上对同一个资源做频控,就自己指定
     *
     * @return key的前缀
     */
    String prefixKey() default "";

    /**
     * 频控对象,默认el表达指定具体的频控对象
     * 对于ip 和uid模式,需要是http入口的对象,保证RequestHolder里有值
     *
     * @return 对象
     */
    Target target() default Target.EL;

    /**
     * springEl 表达式,target=EL必填
     *
     * @return 表达式
     */
    String spEl() default "";

    /**
     * 频控时间范围,默认单位秒
     *
     * @return 时间范围
     */
    int time();

    /**
     * 频控时间单位,默认秒
     *
     * @return 单位
     */
    TimeUnit unit() default TimeUnit.SECONDS;
    enum Target {
        UID, IP, EL
    }
}

aspect


import cn.hutool.core.util.StrUtil;
import cn.tcent.hr.recruit.core.annotation.RepeatSubmit;
import cn.tcent.hr.recruit.core.exception.DataCheckException;
import cn.tcent.hr.recruit.core.utils.RedisUtil;
import cn.tcent.hr.recruit.core.utils.RequestHolder;
import cn.tcent.hr.recruit.core.utils.SpElUtils;
import cn.tcent.hr.recruit.enums.ErrorCode;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @Author 
 * @Description
 * @Date create in 2023-12-26 11:22
 */
@Aspect
@Component
public class RepeatSubmitAspect {

    @Pointcut("@annotation(cn.tcent.hr.recruit.core.annotation.RepeatSubmit)")
    public void authorityPointCut() {
    }

    @Around("authorityPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        RepeatSubmit authentication = method.getAnnotation(RepeatSubmit.class);
        String key = "";
        if (authentication != null) {
            String prefix = StrUtil.isBlank(authentication.prefixKey()) ? SpElUtils.getMethodKey(method) + ":index:" : authentication.prefixKey();//默认方法限定名+注解排名(可能多个)
            switch (authentication.target()) {
                case EL:
                    key = prefix + ":" + SpElUtils.parseSpEl(method, joinPoint.getArgs(), authentication.spEl());
                    break;
                case IP:
                    key = prefix + ":" + RequestHolder.get().getIp();
                    break;
                case UID:
                    key = prefix + ":" + RequestHolder.get().getUid().toString();
            }
        }
        if (StringUtils.isEmpty(key)) {
            return joinPoint.proceed();
        }
        assert authentication != null;
        int time = authentication.time();
        TimeUnit unit = authentication.unit();

        Boolean setnx = RedisUtil.setnx(key, unit.toSeconds(time), "1");
        if (!setnx) {
            throw new DataCheckException(ErrorCode.REPETITIVE_OPERATION.returnCode(), ErrorCode.REPETITIVE_OPERATION.returnDesc());
        }else {
            try {
                return joinPoint.proceed();
            } finally {
                boolean delete = RedisUtil.delete(key);
            }
        }
    }
}
SpElUtils


import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;
import java.util.Optional;

/**
 * Description: spring el表达式解析
 * Author: <a href="https://github.com/zongzibinbin">abin</a>
 * Date: 2023-04-22
 */
public class SpElUtils {
    private static final ExpressionParser parser = new SpelExpressionParser();
    private static final DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    public static String parseSpEl(Method method, Object[] args, String spEl) {
        String[] params = Optional.ofNullable(parameterNameDiscoverer.getParameterNames(method)).orElse(new String[]{});//解析参数名
        EvaluationContext context = new StandardEvaluationContext();//el解析需要的上下文对象
        for (int i = 0; i < params.length; i++) {
            context.setVariable(params[i], args[i]);//所有参数都作为原材料扔进去
        }
        String[] split = spEl.split(",");
        StringBuilder str = new StringBuilder();
        for (String s : split) {
            Expression expression = parser.parseExpression(s);
            str.append(expression.getValue(context, String.class));
        }
        return str.toString();
    }

    public static String getMethodKey(Method method) {
        return method.getDeclaringClass() + "#" + method.getName();
    }
}

使用按钮

    @PostMapping(value = "test-a")
    @ApiOperation(value = "推荐保存接口", httpMethod = "POST")
    @RepeatSubmit(prefixKey="test-a",time=1,unit = TimeUnit.MINUTES,spEl = "#request.applicantName,#request.applicantMail,#request.applicantMobile")
    public ApiResult apply(@RequestBody RecommendRequest request) {
        return new ApiResult<>(ErrorCode.SUCCESS.returnCode(), "推荐成功");
    }

// 或者

    @PostMapping(value = "test-b")
    @RepeatSubmit(prefixKey="signAddress",time=10,spEl = "#signCode,#mobile")
    public ApiResult<String> getSignAddress(@RequestParam("signCode") String signCode, @RequestParam("mobile") String mobile) {
        ApiResult result;
        return result;
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了一套方便的校验注解,可以用于对请求参数进行校验。下面是一些常用的校验注解: 1. @NotNull:验证注解的元素值不为null。 2. @NotEmpty:验证注解的元素值不为null且不为空。 3. @NotBlank:验证注解的元素值不为null且去除首尾空格后不为空。 4. @Min:验证注解的元素值大于等于指定的最小值。 5. @Max:验证注解的元素值小于等于指定的最大值。 6. @Size:验证注解的元素值的大小在指定范围内。 7. @Pattern:验证注解的元素值符合指定的正则表达式。 8. @Email:验证注解的元素值是一个有效的电子邮件地址。 使用这些注解,可以在Controller层的请求参数上进行标记,然后在处理请求的方法中使用@Valid注解进行参数校验。如果校验失败,会抛出MethodArgumentNotValidException异常,可以通过ExceptionHandler进行统一处理。 例如,对一个User对象进行校验: ```java public class User { @NotBlank(message = "用户名不能为空") private String username; @Size(min = 6, max = 20, message = "密码长度必须在6到20之间") private String password; // 省略getter和setter } @RestController public class UserController { @PostMapping("/users") public void createUser(@Valid @RequestBody User user) { // 处理创建用户的逻辑 } // 异常处理 @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Object> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); return ResponseEntity.badRequest().body(errors); } } ``` 在上面的例子中,@NotBlank注解用于校验username字段不能为空,@Size注解用于校验password字段的长度必须在6到20之间。`@Valid`注解用于标记需要进行校验的参数,当校验失败时,会抛出MethodArgumentNotValidException异常,可以通过ExceptionHandler进行统一处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值