1、定义拦截器
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
@Slf4j
public class SlowQueryInterceptor implements Interceptor {
private long queryTimeThreshold;
// 设置慢查询的时间阈值
public void setQueryTimeThreshold(long queryTimeThreshold) {
this.queryTimeThreshold = queryTimeThreshold;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = null;
if (invocation.getArgs().length > 1) {
parameter = invocation.getArgs()[1];
}
long start = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
long end = System.currentTimeMillis();
long executeTime = end - start;
if (executeTime > queryTimeThreshold) {
// 记录慢查询日志
logSlowQuery(mappedStatement, parameter, executeTime);
}
}
}
private void logSlowQuery(MappedStatement ms, Object parameter, long time) {
log.info("-----------------------------------------------------------------");
log.info("查询耗时:" + time +",SQL: "+ms.getBoundSql(parameter).getSql());
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
}
二、注册拦截器
@Configuration
public class FrameMyBatisPluginConfig {
//SQL查询耗时时间设置,超过则打印sql
@Value("${sql.execute.over.time.for.print:4000}")
private long overTime;
@Bean
public String SQLTableNameHandleInterceptor(SqlSessionFactory sqlSessionFactory) {
//实例化插件
SlowQueryInterceptor slowQueryInterceptor = new SlowQueryInterceptor();
//将属性值设置到插件中
slowQueryInterceptor.setQueryTimeThreshold(overTime);
//将插件添加到SqlSessionFactory工厂
sqlSessionFactory.getConfiguration().addInterceptor(slowQueryInterceptor);
return "interceptor";
}
}
三、日志效果