package com.zy.common.config;
|
/**
|
* @author pang.jiabao
|
* @description 记录慢sql日志
|
* @createDate 2024/10/25 16:18
|
*/
|
import org.apache.ibatis.executor.Executor;
|
import org.apache.ibatis.mapping.MappedStatement;
|
import org.apache.ibatis.plugin.*;
|
import org.apache.ibatis.session.ResultHandler;
|
import org.apache.ibatis.session.RowBounds;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import java.util.Properties;
|
|
@Intercepts({
|
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
|
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
|
})
|
public class SlowSqlInterceptor implements Interceptor {
|
|
private static final Logger logger = LoggerFactory.getLogger(com.zy.common.config.SlowSqlInterceptor.class);
|
|
@Override
|
public Object intercept(Invocation invocation) throws Throwable {
|
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
|
String sqlId = ms.getId(); // 获取 SQL ID
|
// 获取 SQL 语句,可以用 sqlSource
|
String sql = ms.getBoundSql(invocation.getArgs()[1]).getSql(); // 获取具体的 SQL 语句
|
|
long startTime = System.currentTimeMillis();
|
Object result = invocation.proceed();
|
long duration = System.currentTimeMillis() - startTime;
|
|
if (duration > 500) { // 阈值
|
logger.warn("慢SQL: {},执行时间: {}毫秒,具体SQL: {}", sqlId, duration, sql);
|
}
|
|
return result;
|
}
|
|
@Override
|
public Object plugin(Object o) {
|
return Plugin.wrap(o, this);
|
}
|
|
@Override
|
public void setProperties(Properties properties) {
|
|
}
|
}
|