AOP统计SQl执行时间

发布于:2024-05-16 ⋅ 阅读:(57) ⋅ 点赞:(0)
package com.example.demo.aspect;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * AOP统计SQl执行时间
 */
@Aspect
@Component
public class SqlExecutionTimeAspect {
    private static final Logger logger = LoggerFactory.getLogger(SqlExecutionTimeAspect.class);

    // jdbc执行SQl时间
    @Pointcut("execution(* org.springframework.jdbc.core.JdbcTemplate.*(..))")
    public void jdbcTemplateMethods() {
    }

    @Around("jdbcTemplateMethods()")
    public Object jdbcMeasureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        logger.info("===== SQL execution time: {} ms", executionTime);
        return result;
    }

    // mybatis执行SQl时间
    @Pointcut("execution(* org.apache.ibatis.executor.Executor.*(..))")
    public void myBatisMethods() {
    }

    @Around("myBatisMethods()")
    public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        logger.info("===== MyBatis execution time: {} ms", executionTime);
        return result;
    }


    // mybatis-plus执行SQl时间
    @Pointcut("execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.*(..))")
    public void myBatisPlusMethods() {
    }

    @Around("myBatisPlusMethods()")
    public Object plusMeasureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        logger.info("===== MyBatis-Plus execution time: {} ms", executionTime);
        return result;
    }
}

注意:在生产环境中,建议关闭执行时间统计功能,以免影响系统性能。可以将切面类的实例化代码注释掉,或者在application.properties中添加以下配置:

logging.level.com.example.demo.aspect.SqlExecutionTimeAspect =OFF

网站公告

今日签到

点亮在社区的每一天
去签到