Spring aop 实现接口幂等

在项目中引入 redis

定义注解类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Idempotent {

    /**
     * 用于拼接幂等性判断的key的入参字段
     *
     * @return
     */
    String[] fields();
    /**
     * 用于接口幂等性校验的Redis中Key的过期时间,单位秒
     * @return
     */
    long timeout() default 10l;
}

定义aop 切面实现类

import cn.hutool.crypto.digest.MD5;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.stereotype.Component;
import org.zalando.problem.Problem;
import org.zalando.problem.Status;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;

@Aspect
@Component
@Slf4j
public class IdempotentAspect {

    @Resource
    private RedisCache redisCache;

  	/**
  		定义切入点
  	*/
    @Pointcut("@annotation(com.*.*.common.annotation.Idempotent)")
    public void pointcut() {
    }

  	// 在进入controller 方法之前进行拦截
    @Before(value = "pointcut() && @annotation(idempotent)")
    public void doBefore(JoinPoint joinPoint, Idempotent idempotent) {
        List<String> args = Lists.newArrayList(idempotent.fields());
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        LinkedHashMap<String, Object> params = Maps.newLinkedHashMap();
        for (int i = 0; i < parameterNames.length; i++) {
            String name = parameterNames[i];
            if (args.contains(name)) {
                params.put(name, joinPoint.getArgs()[i]);
            }
        }
        String paramsStr = JsonUtils.objToString(params);
        String md5 = MD5.create().digestHex(paramsStr.getBytes());
        if(!redisCache.setIfAbsent(md5, md5, 10)){
            throw Problem.valueOf(Status.BAD_REQUEST, "重复提交");
        }
    }
}

在controller 方法中添加@Idempotent注解

@PostMapping("/submit")
@Idempotent(fields = {"info"},timeout = 10)
public OrderInfoResDTO submit(@Valid @RequestBody OrderInfoDTO info) {
 throw Problem.valueOf(Status.BAD_REQUEST, "正常结束流程");
}
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值