Spring Boot之请求重复提交解决(AOP)

2019-06-01  本文已影响0人  yellow_han

1、问题描述

以上情况都有可能导致出现异常数据

2、示例

NoRepeatSubmit.java
package com.hsshy.beam.common.annotion;

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

@Target({ElementType.PARAMETER, ElementType.METHOD}) // 作用到方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时有效
public @interface NoRepeatSubmit {

}
NoRepeatSubmitAspect.java
package com.hsshy.beam.seckill.aspectj;
import com.hsshy.beam.common.utils.R;
import com.hsshy.beam.common.utils.RedisUtil;
import com.hsshy.beam.common.utils.ToolUtil;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Scope
@Aspect
@Order(1)
public class NoRepeatSubmitAspect {

    @Autowired
    private RedisUtil redisUtil;

    //Service层切点     用于记录错误日志
    @Pointcut("@annotation(com.hsshy.beam.common.annotion.NoRepeatSubmit)")
    public void lockAspect() {
        
    }
    
    @Around("lockAspect()")
    public  Object around(ProceedingJoinPoint joinPoint) {
        Object obj = null;
        String key1 = joinPoint.getArgs()[0].toString();
        String key2 = joinPoint.getArgs()[1].toString();
        if(ToolUtil.isNotEmpty(redisUtil.get("repeat_"+key1+":"+key2))){
            System.out.println("重复订单:"+key2);
            return R.fail("订单重复提交");
        }
        else {
            redisUtil.set("repeat_"+key1+":"+key2,"1",2L);
            try {
                    obj = joinPoint.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
                throw new RuntimeException();
            } finally{

            }
            return obj;
        }

    }
}

3、源码地址:https://gitee.com/hsshy/beam-example

上一篇下一篇

猜你喜欢

热点阅读