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>
  • 相关阅读:
    Git学习笔记
    利用GitHub Pages和Hexo搭建个人博客
    dpkg的用法
    Ubuntu 16.04安装有道词典
    Linux 命令之删除命令
    Linux 命令之权限修改
    PHP学习记录第一篇:Ubuntu14.04下LAMP环境的搭建
    ubuntu时钟不显示的解决方法
    kali linux 2.0安装sublime text 2
    折腾kali linux2.0
  • 原文地址:https://www.cnblogs.com/hanfight/p/4752782.html
Copyright © 2011-2022 走看看