Mybatis攔截器實現SQL性能監控


  Mybatis攔截器只能攔截四類對象,分別為:Executor、ParameterHandler、StatementHandler、ResultSetHandler,而SQL數據庫的操作都是從Executor開始,因此要記錄Mybatis數據庫操作的耗時,需要攔截Executor類,代碼實現如下:

/**
 * 數據庫操作性能攔截器,記錄耗時
 * @Intercepts定義Signature數組,因此可以攔截多個,但是只能攔截類型為:
 *         Executor
 *         ParameterHandler
 *         StatementHandler
 *         ResultSetHandler
 * */
@Intercepts(value = { 
        @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,
                CacheKey.class,BoundSql.class}),
        @Signature(type=Executor.class,
        method="query",
        args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
public class TimerInterceptor implements Interceptor {

    private static final Logger logger = Logger.getLogger(TimerInterceptor.class);
    
    /**
     * 實現攔截的地方
     * */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        Object result = null;
        if (target instanceof Executor) {
            long start = System.currentTimeMillis();
            Method method = invocation.getMethod();
            /**執行方法*/
            result = invocation.proceed();
            long end = System.currentTimeMillis();
            logger.info("[TimerInterceptor] execute [" + method.getName() + "] cost [" + (end - start) + "] ms");
        }
        return result;
    }

    /**
     * Plugin.wrap生成攔截代理對象
     * */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}

  完成上面的攔截后,需要將該類在Mybatis配置文件中聲明,如下:

<plugins>
     <!-- SQL性能攔截器 -->
     <plugin interceptor="com.quar.interceptor.TimerInterceptor" />
</plugins>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM