springboot aop注解

目录

1.需求描述

2.实现思路

3.代码实现

3.1添加aspect依赖

3.2新建避免前端重复提交注解@AvoidRepeatable

3.3编写注解aop切面代码


1.需求描述

        实现通过给指定方法添加注解的方式,对添加注解的方法进行重新提交进行控制。

2.实现思路

        新建一个用于标识避免重复的注解@AvoidRepeatable,同时当前后端调用注解标识的方法时,约定一个单次调用唯一凭证uuid,后端收到调用后,先在redis中检测是否有对该方法的uuid缓存,如果有说明前面已有携带该uuid的调用,直接提示重复提交;若在redis中无该uuid的缓存,先在redis中缓存,再执行业务方法,若业务方法执行失败,清除uuid缓存,若业务方法执行成功,不主动清除uuid缓存,通过设置超时时间来清除uuid,用于避免在执行成功后在超时内避免重复提交。

        代码编写顺序:

        1.引入aspect依赖,用于注解aop切面代码编写。

        2.新建避免前端重复提交注解@AvoidRepeatable。

        3.编写注解aop切面代码。

        4.在需要避免重复提交的方法上添加@AvoidRepeatable注解。

3.代码实现

3.1添加aspect依赖

		<!-- aop切面 -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.9.5</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.9.5</version>
		</dependency>

3.2新建避免前端重复提交注解@AvoidRepeatable

package com.ybjdw.product.utils;

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

/**
 * <一句话功能简述> 避免前端重复提交注解
 * <功能详细描述> 在需要保存的方法上添加上,同时要求前端传递唯一参数uuid
 * author: zhanggj
 * 创建时间:  2017年9月7日
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AvoidRepeatable {

}

3.3编写注解aop切面代码

package com.ybjdw.product.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ybjdw.base.utils.ConcurrentUtils;
import com.ybjdw.base.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * author: zhanggw
 * 创建时间:  2021/9/7
 */
@Aspect
@Component
@Lazy(false)
public class AvoidRepeatableAspect {

    private static final Logger logger = LoggerFactory.getLogger(AvoidRepeatableAspect.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 定义切入点:对要拦截的方法进行定义与限制,如包、类
     *
     * 1、execution(public * *(..)) 任意的公共方法
     * 2、execution(* set*(..)) 以set开头的所有的方法
     * 3、execution(* com.ybjdw.annotation.LoggerApply.*(..))com.ybjdw.annotation.LoggerApply这个类里的所有的方法
     * 4、execution(* com.ybjdw.annotation.*.*(..))com.ybjdw.annotation包下的所有的类的所有的方法
     * 5、execution(* com.ybjdw.annotation..*.*(..))com.ybjdw.annotation包及子包下所有的类的所有的方法
     * 6、execution(* com.ybjdw.annotation..*.*(String,?,Long)) com.ybjdw.annotation包及子包下所有的类的有三个参数,第一个参数为String类型,第二个参数为任意类型,第三个参数为Long类型的方法
     * 7、execution(@annotation(com.ybjdw.product.utils.AvoidRepeatable)) 跟随注解
     */
    @Pointcut("@annotation(com.ybjdw.product.utils.AvoidRepeatable)")
    private void cutMethod() {
    }

    /**
     * 前置通知:在目标方法执行前调用
     */
    @Before("cutMethod()")
    public void begin() {
    }

    /**
     * 后置通知:在目标方法执行后调用,若目标方法出现异常,则不执行
     */
    @AfterReturning("cutMethod()")
    public void afterReturning() {
    }

    /**
     * 后置/最终通知:无论目标方法在执行过程中出现一场都会在它之后调用
     */
    @After("cutMethod()")
    public void after() {
    }

    /**
     * 异常通知:目标方法抛出异常时执行
     */
    @AfterThrowing("cutMethod()")
    public void afterThrowing() {
    }

    /**
     * 环绕通知:灵活自由的在目标方法中切入代码
     */
    @Around("cutMethod()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object retObj = null;
        Object[] params = joinPoint.getArgs(); // 方法参数
        String methodName = joinPoint.getSignature().getName(); // 方法名
        try{
            if(params != null && params.length > 0){
                JSONObject dataJson = JSON.parseObject(params[0].toString());
                if(dataJson != null){
                    String uuid = dataJson.getString("uuid"); // 单次唯一凭证
                    if(StringUtils.isBlank(uuid)){
                        return joinPoint.proceed();
                    }

                    String redisKey = methodName + uuid;
                    boolean uniqueRun = ConcurrentUtils.isUniqueRun(redisTemplate, redisKey, 1000*60*3); // 重复检测
                    if(uniqueRun){ // 唯一运行
                        retObj = joinPoint.proceed();
                        if(retObj != null){
                            JSONObject methodReturnJson = JSON.parseObject(retObj.toString());
                            if(!methodReturnJson.getBooleanValue("flag")){ // 方法执行失败清理缓存锁,以便于前端再次提交;成交则保留缓存锁,防止重复提交
                                ConcurrentUtils.freeRedisLock(redisTemplate, redisKey);
                            }
                        }
                    }else{
                        logger.error("product_avoidrepeatable_around_error : methodName:{},uuid:{}重复提交!", methodName, uuid);
                        return HttpUtils.showFail("product_avoidrepeatable_around_error","methodName:"+methodName+",uuid:"+uuid+"重复提交!");
                    }
                }
            }
        }catch (Exception e){
            logger.debug("methodName:{},params:{}",methodName,params);
            logger.error("防止重复提交异常!", e);
        }
        return retObj;
    }

    /**
     * 获取方法中声明的注解
     */
    public AvoidRepeatable getDeclaredAnnotation(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 反射获取目标类
        Class<?> targetClass = joinPoint.getTarget().getClass();
        // 拿到方法对应的参数类型
        Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        // 根据类、方法、参数类型(重载)获取到方法的具体信息
        Method objMethod = targetClass.getMethod(methodName, parameterTypes);
        // 拿到方法定义的注解信息
        AvoidRepeatable annotation = objMethod.getDeclaredAnnotation(AvoidRepeatable.class);
        // 返回
        return annotation;
    }

}

3.4在目标方法上添加注解

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kenick

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值