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中添加以下配置:
logging.level.com.example.demo.aspect.SqlExecutionTimeAspect =OFF