zoukankan      html  css  js  c++  java
  • 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>

    来源:http://www.cnblogs.com/hanfight/p/4752782.html





  • 相关阅读:
    腾讯云通信 资料
    获取openid 的步骤
    微信公众号推送通知接口
    患者接收医生的消息通知完整流程(微信公众号的界面)
    阿里im即时通讯 h5 demo
    微信微信JS-SDK 6.0.2 填坑笔记
    2018秋季寒假作业1-介绍自己
    勿忘初心
    Ubuntu中安装eclipse
    vim的常用指令
  • 原文地址:https://www.cnblogs.com/jeffen/p/6387279.html
Copyright © 2011-2022 走看看