通过mybatis拦截器给sql执行加一个耗时监控

代码没什么内容,直接贴上来吧,其中costTimeUtil可以看我的另一篇博文:java实现一个不带次数变量的加权平均值算法-CSDN博客

复制代码
@Slf4j
@Intercepts({@Signature(
    type = StatementHandler.class,
    method = "query",
    args = {Statement.class, ResultHandler.class}
), @Signature(
    type = StatementHandler.class,
    method = "queryCursor",
    args = {Statement.class}
), @Signature(
    type = StatementHandler.class,
    method = "update",
    args = {Statement.class}
), @Signature(
    type = StatementHandler.class,
    method = "batch",
    args = {Statement.class}
)})
public class MetricOnDbQueryInterceptor implements Interceptor {


  private static final String MAPPER_SLOW_SQL_METRIC = "MetricOnDbQueryInterceptor_cost";
  @Resource
  private AlertOnTimesOfAverageCostTimeUtil costTimeUtil;

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    long start = System.currentTimeMillis();
    try {
      return invocation.proceed();
    } finally {
      String sql = ((StatementHandler) invocation.getTarget()).getBoundSql().getSql();
      long costTime = System.currentTimeMillis() - start;
      if (costTimeUtil.shouldDoTheMetricWork(sql, costTime)) {
        //这里可以做一些监控打点的功能
        log.warn("it is a slow sql query:{}, costTime:{}", sql, costTime);
      }
    }
  }
}
相关推荐
sugar__salt2 小时前
MyBatis ③动态 SQL 完全指南 —— 从条件拼接到批量操作
java·sql·mybatis
元界metalite21 小时前
MyBatis多数据源常见难题-事务开始了为何数据源还没选出来
后端·mybatis
霸道流氓气质1 天前
Mysql中慢 SQL 优化实战:减少不必要的 JOIN 关联
sql·mysql·mybatis
xbgRS2 天前
spring整合mybaits
java·spring·mybatis
vHelios2 天前
【电商项目】商品服务模块的问题解决与代码逻辑思考
java·sql·mybatis
敲个大西瓜3 天前
Mybatis核心面试题
mybatis
砍材农夫3 天前
物联网实战|Spring Boot MQTT平台 |emqx broker实战
spring boot·spring·spring cloud·mybatis
Crazy________3 天前
Redis02:库切换、监控与安全配置
linux·redis·云原生·mybatis
xbgRS4 天前
Mybatis源码-核心流程及核心类
java·mybatis
不谈恋爱的猫5 天前
redis哨兵模式
数据库·redis·mybatis