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>
  • 相关阅读:
    C#委托、事件、消息(入门级)
    WinForm编程数据视图之DataGridView浅析(续)
    WinForm编程数据视图之DataGridView浅析
    在Java窗体表格中插入复选框
    单向链表(单链表)的Java实现
    C#委托、事件、消息(入门级)(续)
    Windows7操作系统自定义运行命令(简单方法之一)
    Unity的外部配置文件使用方法
    aspnet_regsql如何给sqlexpress添加aspnetdb
    联想Y530改装XP经验
  • 原文地址:https://www.cnblogs.com/hanfight/p/4752782.html
Copyright © 2011-2022 走看看