简述何为AOP

AOP为Aspect Oriented Programming的缩写,意思是面向切面编程,通过预编译的方式和运行时动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑进行分离,降低耦合度,提高可重用性,提高开发效率。

主要用途

  1. 日志记录
  2. 事务处理
  3. 异常处理
  4. 安全处理
  5. 性能统计
    ···

在Spring Boot中使用AOP记录接口访问记录

1.添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.编写切面类
@Aspect // @Aspect切面类注解
@Component  // @Component把切面类加入到IOC容器中
public class ShuiBoAspect {

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

    public static long startTime;
    public static long endTime;

    /**
     * execution(public * cn.shuibo.controller.*.*(..))
     * 表示cn.shuibo.controller包下所有类的所有方法, "..."表示所有方法中的参数不限个数
     */
    @Pointcut("execution(public * cn.shuibo.controller.*.*(..))")
    public void shuiboPointcutLog(){

    }
    @Before("shuiboPointcutLog()")
    public void before(JoinPoint joinPoint) {
        startTime = System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        HttpServletRequest request = requestAttributes.getRequest();
        Method method = signature.getMethod();
        String requestURI = request.getRequestURI();
        logger.info("请求URL:" + requestURI);
        String requestMethod = request.getMethod();
        logger.info("请求方式:" + requestMethod);
        Object[] args = joinPoint.getArgs();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + "=" + args[i];
            }
            logger.info("入参:" + params);
        }
        String remoteAddr = request.getRemoteAddr();
        logger.info("IP:" + remoteAddr);
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        logger.info("类名:" + declaringTypeName);
        String methodName = joinPoint.getSignature().getName();
        logger.info("方法名:" + methodName);
    }

    @After("shuiboPointcutLog()")
    public void after() {
        endTime = System.currentTimeMillis() - startTime;
    }

    @AfterReturning(pointcut = "shuiboPointcutLog()", returning = "object")
    public void getAfterReturn(Object object) {
        logger.info("访问耗时:{}ms", endTime);
    }
}
3.编写测试类
@RestController
public class TestController {

    @GetMapping(value = "/index")
    public String index(String text){
        String shuibo = "shuibo.cn";
        if(shuibo.equals(text)){
            shuibo = "https://shuibo.cn";
        }else{
            shuibo = "http://shuibo.cn";
        }
        return shuibo;
    }
}
4.运行结果(控制台)
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 请求URL:http://localhost:8080/index
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 请求方式:GET
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 入参: text=1
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: IP:0:0:0:0:0:0:0:1
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 类名:cn.shuibo.controller.TestController
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 方法名:index
 INFO 10216 --- [nio-8080-exec-1] cn.shuibo.aspect.ShuiBoAspect: 访问耗时:4ms

总结

通过以上实践,我们了解并学习了如何使用Spring Aop切面编程记录访问记录。
本文GitHub地址:https://github.com/ishuibo/SpringAll

   
     
本文作者:      
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
扫码关注不迷路!

发表评论

电子邮件地址不会被公开。 必填项已用*标注