要實現SQL執行時間統計,可以結合MyBatis和Log4j來實現。首先需要在MyBatis的配置文件中配置Log4j的日志輸出,示例如下:
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<properties>
<property name="log4j.rootLogger" value="DEBUG, stdout"/>
<property name="log4j.appender.stdout" value="org.apache.log4j.ConsoleAppender"/>
<property name="log4j.appender.stdout.layout" value="org.apache.log4j.PatternLayout"/>
<property name="log4j.appender.stdout.layout.ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
</properties>
</configuration>
然后在Log4j的配置文件中配置輸出格式和日志級別,示例如下:
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
接著在MyBatis的Mapper接口中使用@Intercepts注解和@Signature注解來實現對SQL執行時間的攔截和統計,示例如下:
@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 SqlStatsInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = invocation.proceed();
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
String sqlId = mappedStatement.getId();
String sql = mappedStatement.getBoundSql(invocation.getArgs()[1]).getSql();
Logger logger = LoggerFactory.getLogger(SqlStatsInterceptor.class);
logger.info("Execute SQL [{}] cost {}ms", sqlId, time);
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
最后,在MyBatis的配置文件中注冊攔截器,示例如下:
<plugins>
<plugin interceptor="com.example.interceptor.SqlStatsInterceptor"/>
</plugins>
通過以上步驟,就可以實現對SQL執行時間的統計并輸出到Log4j日志中。