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
相关推荐
LuckyLay18 分钟前
1.1.1数据类型与变量——AI教你学Django
数据库·django·sqlite
汤姆大聪明1 小时前
Redis 持久化机制
数据库·redis·缓存
brevity_souls2 小时前
什么是时序数据库?——原理、特点与应用
数据库·时序数据库
SelectDB2 小时前
Apache Doris 实时更新技术揭秘:为何在 OLAP 领域表现卓越?
数据库·数据分析·apache
kk在加油3 小时前
Redis数据安全性分析
数据库·redis·缓存
DolphinDB4 小时前
更高效的因子研究工具:基于 DolphinDB 的因子评价框架详解
数据库
此乃大忽悠4 小时前
身份认证缺陷
java·数据库·webgoat·身份认证缺陷
IT项目管理4 小时前
达梦数据库DMDRS搭建单向dm8-dm8数据同步
数据库
咖丨喱5 小时前
【Action帧简要分析】
服务器·数据库·asp.net
没饭吃!5 小时前
NHibernate案例
数据库·hibernate