import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
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.springframework.stereotype.Component;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
*
* @author : ws
* @date : 2021/4/21 19:32
* DESCRIPTION:
*/
@Slf4j
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Component
public class SqlExecuteTimeCountInterceptor implements Interceptor {
/**
* 执行sql时间超过这个时间,提示异常
*/
private static long LIMIT_TIME = 500;
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
/**
* 拦截执行器的方法处理
*
* @param invocation
* @return
* @throws Throwable
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
long start = System.currentTimeMillis();
Object result = invocation.proceed();
long end = System.currentTimeMillis();
long executionTime = end - start;
if (LIMIT_TIME < executionTime) {
String sql = mappedStatement.getBoundSql(invocation.getArgs().length > 1 ? invocation.getArgs()[1] : null).getSql();
log.error("执行SQL方法:[{}] 耗时:[{}ms] \nSQL:[" + sql + "] \n参数:[{}]", mappedStatement.getId(), executionTime, invocation.getArgs().length > 1 ? invocation.getArgs()[1] : "");
}
return result;
}
}
// 在mybatis-config.xml中配置
/**
<configuration>
<plugins>
<plugin interceptor="com.xq.mgxq.api.interceptor.SqlExecuteTimeCountInterceptor"/>
</plugins>
</configuration>
*/