博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybatis(5) -自定义sql拦截统计执行耗时
阅读量:6314 次
发布时间:2019-06-22

本文共 3825 字,大约阅读时间需要 12 分钟。

hot3.png

通过前文了解到 真正执行的Executor是一个invocationHandler为包装了Interceptor的Plugin的代理类

Plugin源码如下:

d407e1c3502b051541f837160d5d9dbadee.jpg

想通过自定义sql执行拦截器来统一打印sql的执行耗时

配置sqlSessionFactory增加Interceptor:

@Bean(name = "sqlSessionFactory")    private SqlSessionFactoryBean sqlSessionFactory(TDataSource mysqlTddlDataSource) throws IOException {        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();        sqlSessionFactoryBean.setDataSource(mysqlTddlDataSource);        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()                .getResources("classpath*:mapper/*Mapper.xml"));        sqlSessionFactoryBean.setPlugins(new Interceptor[] { new SqlStatementInterceptor(ServiceNameConstant.ENGINE)});        return sqlSessionFactoryBean;    }

拦截器: @Signature标识哪样的类在什么样的方法上进行切面。 详见: 

package com.noob.interceptor;import java.util.Properties;import lombok.NoArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.cache.CacheKey;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.plugin.Interceptor;import org.apache.ibatis.plugin.Intercepts;import org.apache.ibatis.plugin.Invocation;import org.apache.ibatis.plugin.Plugin;import org.apache.ibatis.plugin.Signature;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.SerializerFeature;import com.noob.common.constant.CommonConstants;import com.noob.common.constant.CommonConstants.MonitorLogKey;import com.noob.util.CommonUtil;import com.noob.util.NetUtil;/** * 数据库操作性能拦截器,记录耗时 */@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 }) })@NoArgsConstructor@Slf4jpublic class SqlStatementInterceptor implements Interceptor {    private Properties properties;    private String     hostIp;    public SqlStatementInterceptor(String appName) {        properties = new Properties();        properties.setProperty(MonitorLogKey.PROJECT_NAME, appName);        hostIp = NetUtil.getLocalAddress();    }    @Override    public Object intercept(Invocation arg0) throws Throwable {        MappedStatement mappedStatement = (MappedStatement) arg0.getArgs()[0];        String sqlId = mappedStatement.getId();        Object returnValue;        long start = System.currentTimeMillis();        returnValue = arg0.proceed();        long end = System.currentTimeMillis();        log(sqlId, end - start);        return returnValue;    }    private void log(String sqlId, long costTime) {        try {            JSONObject logObj = CommonUtil.createGrafanaLog();            logObj.put(MonitorLogKey.LOG_TYPE, CommonConstants.MonitorType.SQL_MONITOR);//sql 耗时            logObj.put(MonitorLogKey.PROJECT_NAME, properties.get(MonitorLogKey.PROJECT_NAME));            logObj.put(MonitorLogKey.HOST_IP, hostIp);            logObj.put("sql", sqlId);            logObj.put("costTime", costTime);            log.info(JSONObject.toJSONString(logObj, SerializerFeature.UseISO8601DateFormat));        } catch (Exception e) {            log.warn("output sql costTime fail.", e);        }    }    @Override    public Object plugin(Object arg0) {        return Plugin.wrap(arg0, this);    }    @Override    public void setProperties(Properties arg0) {        this.properties = arg0;    }}

 

转载于:https://my.oschina.net/u/3434392/blog/3010600

你可能感兴趣的文章
CentOS 6.9通过RPM安装EPEL源(http://dl.fedoraproject.org)
查看>>
“区块链”并没有什么特别之处
查看>>
没有功能需求设计文档?对不起,拒绝开发!
查看>>
4星|《先发影响力》:影响与反影响相关的有趣的心理学研究综述
查看>>
IE8调用window.open导出EXCEL文件题目
查看>>
python之 列表常用方法
查看>>
vue-cli脚手架的搭建
查看>>
在网页中加入百度搜索框实例代码
查看>>
在Flex中动态设置icon属性
查看>>
采集音频和摄像头视频并实时H264编码及AAC编码
查看>>
3星|《三联生活周刊》2017年39期:英国皇家助产士学会于2017年5月悄悄修改了政策,不再鼓励孕妇自然分娩了...
查看>>
高级Linux工程师常用软件清单
查看>>
堆排序算法
查看>>
folders.cgi占用系统大量资源
查看>>
路由器ospf动态路由配置
查看>>
zabbix监控安装与配置
查看>>
python 异常
查看>>
last_insert_id()获取mysql最后一条记录ID
查看>>
可执行程序找不到lib库地址的处理方法
查看>>
bash数组
查看>>