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

本文介绍了一个Java拦截器MetricOnDbQueryInterceptor,用于监控SQL查询的执行时间,当查询耗时超过阈值时记录并报警,同时提及了与costTimeUtil相关的加权平均值算法应用。
摘要由CSDN通过智能技术生成

代码没什么内容,直接贴上来吧,其中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);
      }
    }
  }
}

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慢一点,细一点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值