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





  • 相关阅读:
    当前网页调用其他网页
    保护自己的网页不被放入框架
    保护网页源码
    页面的后退、刷新、前进
    妙味——拖拽+碰撞+重力
    运行代码
    妙味——弹性运动
    IE css bug及解决方案参考
    妙味——布局转换的应用
    [LeetCode][JavaScript]Count Complete Tree Nodes
  • 原文地址:https://www.cnblogs.com/jeffen/p/6387279.html
Copyright © 2011-2022 走看看