概要
- mybatisを使用したアプリケーションでSQLの実行時間を取得したいと思った
- mybatisのInterceptorを使えばできそうだったので実装してみた
コード
- Interceptorを実装したクラスをBean登録したらOK!
MyInterceptor
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
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}
)
})
@Component
@Slf4j
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement statement = (MappedStatement)invocation.getArgs()[0];
long start = System.currentTimeMillis();
Object result = invocation.proceed();
long end = System.currentTimeMillis();
String[] items = statement.getId().split("\\.");
log.info("{} ms. class: {}, method: {}", end - start, items[items.length - 2], items[items.length - 1]);
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
※そもそもMybatisの機能として実行時間くらい取得できそうな気もするが、
これができればいろんな処理が注入できるので、勉強にはなったかな!