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
相关推荐
格调UI成品2 小时前
预警系统安全体系构建:数据加密、权限分级与误报过滤方案
大数据·运维·网络·数据库·安全·预警
心平愈三千疾6 小时前
通俗理解JVM细节-面试篇
java·jvm·数据库·面试
Lx3527 小时前
排序缓冲区调优:sort_buffer_size的合理配置
sql·mysql·性能优化
我科绝伦(Huanhuan Zhou)9 天前
Oracle|Oracle SQL*Plus 配置上下翻页功能
数据库·sql·oracle
Cachel wood9 天前
Spark教程6:Spark 底层执行原理详解
大数据·数据库·分布式·计算机网络·spark
java—大象9 天前
基于java SSM的房屋租赁系统设计和实现
java·开发语言·数据库·spring boot·layui·mybatis
Mutig_s9 天前
Spring Boot动态数据源切换:优雅实现多数据源管理
java·数据库·spring boot·后端·mybatis
Python小老六9 天前
单片机测ntc热敏电阻的几种方法(软件)
数据库·单片机·嵌入式硬件
矿渣渣9 天前
SQLite3 在嵌入式系统中的应用指南
数据库·sqlite·嵌入式实时数据库