AOP统计SQl执行时间

java 复制代码
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中添加以下配置:

properties 复制代码
logging.level.com.example.demo.aspect.SqlExecutionTimeAspect =OFF
相关推荐
运维行者_4 小时前
Applications Manager中的Redis监控
大数据·服务器·数据库·人工智能·网络协议
悦数图数据库7 小时前
图数据库选型指南 2026:从架构、性能、AI 适配三个维度看 悦数科技
数据库·人工智能·架构
handler018 小时前
【MySQL】常用命令总结(库与表增删查改)
运维·数据库·mysql·命令·总结
week@eight8 小时前
Linux - Doris
linux·运维·数据库·mysql
cdbqss19 小时前
VB2026 菜单生成基类 BqGetMenuStrip
数据库·经验分享·学习·oracle·vb
洛水水9 小时前
Redis 分布式锁详解:实现与缺陷
数据库·redis·分布式
韶博雅9 小时前
oracle中表和列转大写
数据库·oracle
暴躁小师兄数据学院10 小时前
【AI大数据工程师特训笔记】第04讲:PostgreSQL 数据库内置函数详解
大数据·数据库·笔记·ai·语言模型
JAVA面经实录91710 小时前
MyBatis学习体系
java·mybatis