𝓝𝓮𝓶𝓸&博客

【Spring】面向切面编程AOP,自定义注解

AOP

面向切面编程(AOP, Aspect Oriented Programming)

概念

  1. 什么是 AOP
    1. 面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
    2. 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
    3. 使用登录例子说明 AOP

底层原理

  1. AOP 底层使用动态代理
    有两种情况动态代理
    1. 第一种 有接口情况,使用 JDK 动态代理

    创建接口实现类代理对象,增强类的方法

    1. 第二种 没有接口情况,使用 CGLIB 动态代理

    创建子类的代理对象,增强类的方法

JDK 动态代理

  1. 使用 JDK 动态代理,使用 Proxy 类里面的方法创建代理对象
    1. 调用 newProxyInstance 方法
      方法有三个参数:
      1. 第一参数,类加载器
      2. 第二参数,增强方法所在的类,这个类实现的接口,支持多个接口
      3. 第三参数,实现这个接口 InvocationHandler,创建代理对象,写增强的部分
  2. 编写 JDK 动态代理代码
    1. 创建接口,定义方法

      public interface UserDao {
          public int add(int a,int b);
          public String update(String id);
      }
      
    2. 创建接口实现类,实现方法

      public class UserDaoImpl implements UserDao {
          @Override
          public int add(int a, int b) {
              return a+b;
          }
          @Override
          public String update(String id) {
              return id;
          } 
      }
      
    3. 使用 Proxy 类创建接口代理对象

      public class JDKProxy {
          public static void main(String[] args) {
              //创建接口实现类代理对象
              Class[] interfaces = {UserDao.class};
          // Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
          //     @Override
          //     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          //          return null;
          //     }
          // });
              UserDaoImpl userDao = new UserDaoImpl();
              UserDao dao = 
                  (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
              int result = dao.add(1, 2);
               System.out.println("result:"+result);
          } 
      }
      
      //创建代理对象代码
      class UserDaoProxy implements InvocationHandler {
          //1 把创建的是谁的代理对象,把谁传递过来
          //有参数构造传递
          private Object obj;
          public UserDaoProxy(Object obj) {
              this.obj = obj;
          }
          //增强的逻辑
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
              //方法之前
              System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.toString(args));
              //被增强的方法执行
              Object res = method.invoke(obj, args);
              //方法之后
              System.out.println("方法之后执行...."+obj);
              return res;
          } 
      }
      

术语

  1. 连接点:类里面哪些方法可以被增强,这些方法称为连接点
  2. 切入点:实际被真正增强的方法,称为切入点
  3. 通知(增强):
    1. 实际增强的逻辑部分称为通知(增强)
    2. 通知有多种类型
      • 前置通知
      • 后置通知
      • 环绕通知
      • 异常通知
      • 最终通知
  4. 切面:是动作,把通知应用到切入点的过程

AOP 操作

准备工作

  1. Spring 框架一般都是基于 AspectJ 实现 AOP 操作
    1. AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使用,进行 AOP 操作
  2. 基于 AspectJ 实现 AOP 操作
    1. 基于 xml 配置文件实现
    2. 基于注解方式实现(使用)
  3. 在项目工程里面引入 AOP 相关依赖
  4. 切入点表达式
    1. 切入点表达式作用:知道对哪个类里面的哪个方法进行增强
    2. 语法结构:execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]))

    举例 1:对 com.nemo.dao.BookDao 类里面的 add 进行增强
    execution(* com.nemo.dao.BookDao.add(..))
    举例 2:对 com.nemo.dao.BookDao 类里面的所有的方法进行增强
    execution(* com.nemo.dao.BookDao.* (..))
    举例 3:对 com.nemo.dao 包里面所有类,类里面所有方法进行增强
    execution(* com.nemo.dao.*.* (..))

AspectJ 注解

  1. 创建类,在类里面定义方法

    public class User {
        public void add() {
            System.out.println("add.......");
        } 
    }
    
  2. 创建增强类(编写增强逻辑)

    1. 在增强类里面,创建方法,让不同方法代表不同通知类型

      //增强的类
      public class UserProxy {
          public void before() {//前置通知
              System.out.println("before......");
          } 
      }
      
  3. 进行通知的配置

    1. 在 spring 配置文件中,开启注解扫描

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xmlns:context="http://www.springframework.org/schema/context" 
             xmlns:aop="http://www.springframework.org/schema/aop" 
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
       <!-- 开启注解扫描 -->
       <context:component-scan base￾package="com.nemo.spring5.aopanno"></context:component-scan>
      
    2. 使用注解创建 User 和 UserProxy 对象

    3. 在增强类上面添加注解 @Aspect

      //增强的类
      @Component
      @Aspect //生成代理对象
      public class UserProxy {
      
    4. 在 spring 配置文件中开启生成代理对象

      <!-- 开启 Aspect 生成代理对象-->
      <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
      
  4. 配置不同类型的通知

    1. 在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

      //增强的类
      @Component
      @Aspect //生成代理对象
      public class UserProxy {
          //前置通知
          //@Before 注解表示作为前置通知
          @Before(value = "execution(* com.nemo.spring5.aopanno.User.add(..))")
          public void before() {
              System.out.println("before.........");
          }
          //后置通知(返回通知)
          @AfterReturning(value = "execution(* com.nemo.spring5.aopanno.User.add(..))")
          public void afterReturning() {
              System.out.println("afterReturning.........");
          }
          //最终通知
          @After(value = "execution(* com.nemo.spring5.aopanno.User.add(..))")
          public void after() {
              System.out.println("after.........");
          }
          //异常通知
          @AfterThrowing(value = "execution(* com.nemo.spring5.aopanno.User.add(..))")
          public void afterThrowing() {
              System.out.println("afterThrowing.........");
          }
          //环绕通知
          @Around(value = "execution(* com.nemo.spring5.aopanno.User.add(..))")
          public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
              System.out.println("环绕之前.........");
              //被增强的方法执行
              proceedingJoinPoint.proceed();
              System.out.println("环绕之后.........");
          }
      }
      
  5. 相同的切入点抽取

    //相同切入点抽取
    @Pointcut(value = "execution(* com.nemo.spring5.aopanno.User.add(..))")
    public void pointdemo() {
    }
    //前置通知
    //@Before 注解表示作为前置通知
    @Before(value = "pointdemo()")
    public void before() {
        System.out.println("before.........");
    }
    
  6. 有多个增强类多同一个方法进行增强,设置增强类优先级

    1. 在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

      @Component
      @Aspect
      @Order(1)
      public class PersonProxy
      
  7. 完全使用注解开发

    1. 创建配置类,不需要创建 xml 配置文件

      @Configuration
      @ComponentScan(basePackages = {"com.nemo"})
      @EnableAspectJAutoProxy(proxyTargetClass = true)
      public class ConfigAop {
      }
      

AspectJ 配置文件

  1. 创建两个类,增强类和被增强类,创建方法

  2. 在 spring 配置文件中创建两个类对象

    <!--创建对象-->
    <bean id="book" class="com.nemo.spring5.aopxml.Book"></bean>
    <bean id="bookProxy" class="com.nemo.spring5.aopxml.BookProxy"></bean>
    
  3. 在 spring 配置文件中配置切入点

    <!--配置 aop 增强--> <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* com.nemo.spring5.aopxml.Book.buy(..))"/>
        <!--配置切面-->
        <aop:aspect ref="bookProxy">
            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>
    

应用场景

使用Component进行全局方法截取输出日志

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

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

/**
 * @author nemo
 */
@Slf4j
@Component
@Aspect
public class RequestContentLogAspect {
    /**
     * log请求内容
     *
     * @param joinPoint
     */
    @Before("within(com.plat.controller.*)")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        log.info("{}.{} request content: ({})",
                method.getDeclaringClass(), method.getName(), StringUtils.join(args, ", "));
    }

    /**
     * log返回内容
     *
     * @param joinPoint
     * @param response
     */
    @AfterReturning(value = "within(com.plat.controller.*)",
            returning = "response")
    public void after(JoinPoint joinPoint, Object response) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        log.info("{}.{} return: {}",
                method.getDeclaringClass(), method.getName(),
                Objects.isNull(response) ? "null" : response.toString());
    }
}

输出日志:

2021-08-30 14:04:35.545  INFO 70296 [http-nio-8480-exec-7] --- c.b.a.p.d.p.a.RequestContentLogAspect    : [][][RequestContentLogAspect.java:before:33] class com.plat.controller.FaqController.list request content: (, 1, , [-1], [-1], createTime, asc, 1, 10)

通过注解记录方法处理时长输出日志

注解:

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

/**
 * 注解在方法上,方法需要在日志里输出处理时长
 *
 * @author nemo
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RecordPerformance {
}

Component:

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 记录log的切面
 *
 * @author nemo
 */
@Slf4j
@Aspect
@Component
public class PerformanceLogAspect {
    /**
     * 记录性能,处理时长
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around(value =
            "@annotation(com.plat.annotation.RecordPerformance)"
    )
    public Object recordPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        var result = joinPoint.proceed();   // 执行切点的方法
        long costTime = System.currentTimeMillis() - startTime;

        var targetMethod = ((MethodSignature) joinPoint.getSignature()).getMethod();

        log.info("{}.{} process cost {}ms", targetMethod.getDeclaringClass(), targetMethod.getName(), costTime);
        return result;
    }
}

使用:

/**
 * @author nemo
 */
public class Test {

    /**
     * 计算图片内容的md5来做作为新的文件名
     *
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     */
    @RecordPerformance
    public String newFileName(Request request) {

        var bytesOfMessage = request.getImageBase64().getBytes();

        String fileName;
        try {
            var messageDigest = MessageDigest.getInstance("MD5");

            byte[] digest = messageDigest.digest(bytesOfMessage);
            String contentDigest = DatatypeConverter
                    .printHexBinary(digest).toUpperCase();

            String[] fragment = new String[] {
                    contentDigest, String.valueOf(System.currentTimeMillis())
            };
            fileName = StringUtils.join(fragment, "-");
        } catch (NoSuchAlgorithmException e) {
            fileName = UUID.randomUUID().toString();
            log.warn("Fail to use md5 algorithm to generate file name, replace with uuid: {}", fileName, e);
        }

        return fileName + "." + StringUtils.substringAfterLast(request.getName(), ".");
    }
}

输出日志:

2021-12-28 15:35:03.051  INFO 19539 [http-nio-8480-exec-4] --- c.b.a.p.d.p.aspect.PerformanceLogAspect  : [][][PerformanceLogAspect.java:recordPerformance:36] class com.plat.controller.Test.newFileName process cost 1ms

注解限制重复提交

处理的方式有两种,本次介绍普适性方案,解决问题1。

  1. 正常业务请求的防止限制
  2. 极端情况下的请求,rediskey过期带来的重复请求。

代码结构比较清晰,直接贴代码啦:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LimitSubmit {
    String key() ;
    /**
     * 默认 10s
     */
    int limit() default 10;

    /**
     * 请求完成后 是否一直等待
     * true则等待
     * @return
     */
    boolean needAllWait() default true;
}
@Component
@Aspect
@Slf4j
public class LimitSubmitAspect {
    //封装了redis操作各种方法
    @Autowired
    private RedisUtil redisUtil;

    @Pointcut("@annotation(org.jeecg.common.aspect.annotation.LimitSubmit)")
    private void pointcut() {}

    @Around("pointcut()")
    public Object handleSubmit(ProceedingJoinPoint joinPoint) throws Throwable {
        LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取注解信息
        LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class);
        int submitTimeLimiter = limitSubmit.limit();
        String redisKey = limitSubmit.key();
        boolean needAllWait = limitSubmit.needAllWait();
        String key =  getRedisKey(sysUser,joinPoint, redisKey);
        Object result = redisUtil.get(key);
        if (result != null) {
            throw new JeecgBootException("请勿重复访问!");
        }
        redisUtil.set(key, sysUser.getId(), submitTimeLimiter);
        try {
            Object proceed = joinPoint.proceed();
            return proceed;
        } catch (Throwable e) {
            log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
            throw e;
        }finally {
            if(!needAllWait) {
                redisUtil.del(redisKey);
            }
        }
    }

    /**
     * 支持多参数,从请求参数进行处理
     */
    private String getRedisKey(LoginUser sysUser, ProceedingJoinPoint joinPoint, String key){
        if(key.contains("%s")) {
            key = String.format(key, sysUser.getId());
        }
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = discoverer.getParameterNames(method);
        if (parameterNames != null) {
            for (int i = 0; i < parameterNames.length; i++) {
                String item = parameterNames[i];
                if(key.contains("#"+item)){
                    key = key.replace("#"+item, joinPoint.getArgs()[i].toString());
                }
            }
        }
        return key.toString();
    }
}

使用效果:
image

/* 
使用:
	%s 代表当前登录人
	#参数 代表从参数中获取,支持多个参数
*/
@LimitSubmit(key = "testLimit:%s:#orderId",limit = 10,needAllWait = true)
// 生成的redis key: testLimit:e9ca23d68d884d4ebb19d07889727dae:order1123123
  1. 限制对某个接口的访问,针对所有人,则去除%s
  2. 限制某个人对某个接口的访问,则 %s
  3. 限制某个人对某个接口的业务参数的访问,则 %s:#参数1:#参数2

image
image

posted @ 2020-08-07 17:32  Nemo&  阅读(4321)  评论(0编辑  收藏  举报