package com.pacmp.config.interceptors; import lombok.extern.slf4j.Slf4j; 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 java.util.Properties; /** * @Author * @Date 2020/7/29 14:19 * @Version 版本号 * @Description mybatis执行sql耗时 */ @Slf4j @Intercepts({ @Signature( type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class} ), @Signature( type = Executor.class, method = "update", args = {MappedStatement.class, Object.class} ) }) public class SqlStatementInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { long startTime = System.currentTimeMillis(); try { return invocation.proceed(); } finally { long timeConsuming = System.currentTimeMillis()-startTime; log.debug("执行SQL:{}ms", timeConsuming); if(timeConsuming>999&&timeConsuming<5000){ log.debug("执行SQL大于1s:{}ms", timeConsuming); }else if(timeConsuming>=5000&&timeConsuming<10000){ log.debug("执行SQL大于5s:{}ms", timeConsuming); }else if(timeConsuming>=10000){ log.debug("执行SQL大于10s:{}ms", timeConsuming); } } } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
package com.pacmp.config; import com.alibaba.druid.pool.DruidDataSource; import com.pacmp.config.interceptors.SqlStatementInterceptor; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.Resource; /** * @Author * @Date 2020/7/29 14:28 * @Version 版本号 * @Description mybatis执行sql耗时 */ @Configuration public class MyBatisConfig { @Resource private DruidDataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setPlugins(new Interceptor[]{new SqlStatementInterceptor()}); PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources("classpath*:mapper/*.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.pacmp.mapper"); return sqlSessionFactoryBean.getObject(); } }