Flowable自定义MyBatis拦截器

版权声明:本文为博主原创文章,未经博主允许不得转载。不经过允许copy,讲追究法律责任,欢迎加入我们的学习提升群523988350,可以相互交流 https://blog.csdn.net/qq_30739519/article/details/85640670

众所周知,Flowable使用的是Mybatis框架进行数据库的CRUD操作,有时候我们想打印这些查询或者更新sql一共耗费了多长时间,这个时候我们就期望使用Mybatis的拦截器进行一些sql的拦截和sql执行时间的统计。如题步骤如下:

1、自定义Mybatis拦截器

@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.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 = "update", args = { MappedStatement.class, Object.class})
})
public class LogSqlExecutionTimePlugin implements Interceptor {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(LogSqlExecutionTimePlugin.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object retVal = invocation.proceed();
        long endTime = System.currentTimeMillis();
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        LOGGER.debug("SQL Statement {} took {}ms", mappedStatement.getId(), endTime-startTime);
        return retVal;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

上述的代码总结如下:

1、拦截所有的query以及update方法。

2、实现Interceptor接口,并重写intercept方法。

3、intercept进行了sql耗费时间的统计。

4、类似这样的拦截器可以根据项目自身情况进行书写就好。

2、将拦截器注入引擎

自定义流程引擎配置类并重写

AbstractEngineConfiguration类中的initMybatisTypeHandlers方法即可。代码如下:
public void initMybatisTypeHandlers(Configuration configuration) {
        // To be extended

configuration.addInterceptor(new ShareniuLogSqlExecutionTimePlugin());
}

3、内置拦截器

Flowable其实也内置了我们上述的日志拦截器功能,默认没有开启,我们需要开启一下,操作如下:

 <property name="enableLogSqlExecutionTime" value="true" />

4、拦截器遗留问题

目前Flowable并没有为我们开发人员提供一些开关属性用于添加一系列的拦截器,后续我会根据情况进行PR。期待下一个版本我的PR。

猜你喜欢

转载自blog.csdn.net/qq_30739519/article/details/85640670