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
相关推荐
while(1){yan}1 小时前
Mybatis基础(详解)
spring boot·spring·java-ee·mybatis
知行学思1 小时前
Python配置管理完全指南:从dotenv到pydantic_settings
数据库·python·fastapi·环境变量·配置管理·pydantic·dotenv
计算机网恋1 小时前
Ubuntu22.04Server虚拟机网络配置
网络·数据库·postgresql
多多*4 小时前
2026年1月3日八股记录
java·开发语言·windows·tcp/ip·mybatis
一只大黄猫5 小时前
【数据库-入门2】基本概念
数据库
实泽有之,无泽虚之6 小时前
MySQL主机因多次连接数据库错误而被阻塞
数据库·sql·mysql
Knight_AL7 小时前
从自然语言到 SQL:为什么向量数据库是更好的选择
数据库·sql
草原印象7 小时前
Spring、SpringMVC、Mybatis框架整合实战视频课程
java·spring·mybatis
Maybe I Simple8 小时前
MySql 数据库分表 简单思路
数据库·php·webman
智航GIS8 小时前
8.11 sys 模块
数据库·windows·microsoft