aop注解处理重复请求

/**
* @Description: 重复请求
* @Author: Nathan Wang
* @Date: 2020-6-12 11:30
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NotDuplicate {
    long timeout() default 3;
}

 

@Aspect
@Component
public class NotDuplicateAop {

    private static final String KEY = "DUPLICATE_METHOD_";
    @Autowired
    private JedisUtils jedisUtils;

    @Pointcut("@annotation(com.km.config.duplicate.NotDuplicate)")
    public void duplicate() {
    }

    /**
     * 对方法拦截后进行参数验证
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("duplicate()")
    public Object duplicate(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature msig = (MethodSignature) pjp.getSignature();
        Method currentMethod = pjp.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes());
        NotDuplicate notDuplicate = currentMethod.getAnnotation(NotDuplicate.class);
        //拼接签名
        StringBuilder sb = new StringBuilder(currentMethod.getName());
        Object[] args = pjp.getArgs();
        for (Object object : args) {
            if(object != null){
                sb.append(object.getClass().toString());
                sb.append(object.toString());
            }
        }
        String sign = sb.toString();
        ValueOperations<String, String> template = jedisUtils.getStringRedisTemplate();
        Boolean getLock = template.setIfAbsent(KEY+sign, "1");
        if (!getLock){
            throw new RuntimeException("该方法正在执行,不能重复请求" + currentMethod.getName());
        }
        jedisUtils.getRedisTemplate().expire(KEY+sign, notDuplicate.timeout(), TimeUnit.SECONDS);
        return pjp.proceed();
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值