(SpringBoot)注解+切面实现日志管理等功能

前言:

        基于SpringBoot项目。切面编程为了实现代码的复用性。和一些公共功能的处理。如日志管理、接口耗时打印、接口鉴权等。此时使用切面编程最佳不过。

        业务场景:本系统需要调用一些外部开源API(如阿里云、百度AI开放平台等),对接接口较多切比较耗时。所以写一个记录接口耗时的查看实际应用到业务场景后会不会超过工程默认接口超时时间,以便后面进行调整。

一、代码实现

        1、依赖导入(Maven)

        除了SpringBoot基本的依赖之外(spring-boot-starter-web)外还需要导入AOP依赖

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

        2、编写@interface接口

//注解作用范围(类上、方法上、属性上) 此为方法上
@Target(ElementType.METHOD)
//运行环境
@Retention(RetentionPolicy.RUNTIME)
public @interface TakeUpTime {
    
    //接口编写时输入,接口中文名
    String value() default "";
}

        3、编写切面实现类

package org.java.demo.springbootdemo.aspect;

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.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

//声明这是切面AOP类,后面的程序时将此类代理
@Aspect
//注入到spring容器
@Component
//日志打印工具
@Slf4j
public class TakeUpTimeAspect {

    //切入点                类似监听范围                   controller包下的所有类、方法    监听的注解是    刚编写的@InterFace 路径
    @Pointcut("execution(public * org.java.demo.springbootdemo.controller.*.*(..))&&@annotation(org.java.demo.springbootdemo.aspect.TakeUpTime)")
    public void timeInterface(){}

    //类型:环绕通知   切入点
    @Around("timeInterface()")
    public Object roundAdvice(ProceedingJoinPoint point) throws Throwable {
        //声明Object 准备接收返回值
        Object result = null;
        long startTime = System.currentTimeMillis();
        //获取入参,有时对入参过滤可以使用。
        Object[] args = point.getArgs();
        //别切入方法所有信息
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取该方法注解上的属性参数
        TakeUpTime annotation = signature.getMethod().getAnnotation(TakeUpTime.class);
        String value = annotation.value();
        //执行添加注解的方法
        result = point.proceed();
        Long time = System.currentTimeMillis() - startTime;
        //获取方法名称
        String methodName = signature.getName();
        log.info("方法名称:{}",methodName);
        log.info("{}-API的{}方法耗时{}毫秒",value,methodName,time);
        log.info("耗时:{}毫秒",time.toString());
        return result;
    }
}

                注意的是类上的注解不要忘记。@slf4j 看实际业务是否需要

        4、编写接口controller实现

@RestController
@RequestMapping("/aop")
public class AopController {


@GetMapping("/baidu")
    @TakeUpTime("百度")
    public String baiduApi() throws InterruptedException {
        //模拟接口耗时
        Thread.sleep(1000);
        return "SUCCESS~";
    }

    @GetMapping("/alibaba")
    @TakeUpTime("阿里")
    public String alibaba() throws InterruptedException {
        //模拟接口耗时
        Thread.sleep(800);
        return "SUCCESS~";
    }

}

/*调用localhost:8080/aop/baidu
打印如下:
方法名称:baiduApi
百度-API的baiduApi方法耗时1022毫秒
耗时:1022毫秒  */

/*调用localhost:8080/aop/alibaba
打印如下:
方法名称:alibaba
阿里-API的alibaba方法耗时807毫秒
耗时:807毫秒  */

       总结:

                好了,这就时注解+aop实现了最简单的注解形式的切面操作了。后面的高端用法还需要探索。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot实现环绕切面监控接口异常信息并打印logger日志,可以按照以下步骤进行: 1. 创建一个切面类,并标注@Aspect注解,用于定义切面的具体实现代码。 ```java @Aspect @Component public class ExceptionAspect { @Around("execution(* com.example.demo.controller.*.*(..))") public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; try { result = joinPoint.proceed(); } catch (Exception e) { Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass()); logger.error("接口异常信息:{},异常堆栈信息:{}", e.getMessage(), e); throw e; } return result; } } ``` 2. 在切面类中定义一个环绕通知方法,用于拦截指定的接口请求,并处理接口异常信息。在通知方法中,可以使用ProceedingJoinPoint参数调用目标方法并获取方法执行结果。如果方法执行过程中出现异常,可以使用Logger打印异常信息,并将异常重新抛出,以便后续处理。 3. 在切面类上添加@Component注解,将切面类注册到Spring容器中。 4. 在Spring Boot的配置文件中,添加以下配置,启用AOP切面功能。 ```properties spring.aop.auto=true ``` 通过以上步骤,就可以在Spring Boot应用中实现环绕切面监控接口异常信息并打印logger日志功能。在应用程序执行过程中,如果接口出现异常,就会在控制台或日志文件中打印异常信息,方便开发人员进行排查和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值