通过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);
      }
    }
  }
}
相关推荐
xbhog5 小时前
Java大厂面试突击:从Spring Boot自动配置到Kafka分区策略实战解析
spring boot·kafka·mybatis·java面试·分布式架构
爱的叹息5 小时前
MyBatis缓存配置的完整示例,包含一级缓存、二级缓存、自定义缓存策略等核心场景,并附详细注释和总结表格
缓存·mybatis
PXM的算法星球7 小时前
【Java后端】MyBatis 与 MyBatis-Plus 如何防止 SQL 注入?从原理到实战
java·sql·mybatis
旧故新长7 小时前
MyBatis 类型处理器(TypeHandler)注册与映射机制:JsonListTypeHandler和JsonListTypeHandler注册时机
java·开发语言·mybatis
wkj00113 小时前
springboot + mybatis 需要写 .xml吗
xml·spring boot·mybatis
爱的叹息1 天前
Spring和Spring Boot集成MyBatis的完整对比示例,包含从项目创建到测试的全流程代码
spring boot·spring·mybatis
与秋逐鹿¥1 天前
在Mybatis中为什么要同时指定扫描mapper接口和 mapper.xml 文件,理论单独扫描 xml 文件就可以啊
java·tomcat·mybatis
爱的叹息1 天前
MyBatis 插件开发的完整详细例子
mybatis
Minyy112 天前
SpringBoot程序的创建以及特点,配置文件,LogBack记录日志,配置过滤器、拦截器、全局异常
xml·java·spring boot·后端·spring·mybatis·logback
北辰浮光2 天前
[Mybatis-plus]
java·开发语言·mybatis