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
相关推荐
Zfox_1 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
陈丹阳(滁州学院)3 小时前
若依添加添加监听容器配置(删除键,键过期)
数据库·oracle
远方16094 小时前
14-Oracle 23ai Vector Search 向量索引和混合索引-实操
数据库·ai·oracle
GUIQU.5 小时前
【Oracle】数据仓库
数据库·oracle
恰薯条的屑海鸥5 小时前
零基础在实践中学习网络安全-皮卡丘靶场(第十六期-SSRF模块)
数据库·学习·安全·web安全·渗透测试·网络安全学习
咖啡啡不加糖6 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
曼汐 .6 小时前
数据库管理与高可用-MySQL高可用
数据库·mysql
2301_793102496 小时前
Linux——MySql数据库
linux·数据库
喵叔哟6 小时前
第4章:Cypher查询语言基础
数据库
刘 大 望6 小时前
数据库-联合查询(内连接外连接),子查询,合并查询
java·数据库·sql·mysql