【问题标题】:Logging JdbcTemplate query execution time记录 JdbcTemplate 查询执行时间
【发布时间】:2017-06-20 14:46:49
【问题描述】:

我正在编写一个通过org.springframework.jdbc.core.JdbcTemplate 使用db 的应用程序。我需要记录这些查询的执行。所以我有一些具有一些 jdbctemplate 逻辑的方法,例如

List<Map<String, Object>> data = jdbcTemplate.queryForList(queryTables);

我需要记录此查询的执行时间,而不是所有方法的执行时间。 我可以通过毫秒减法来做到这一点。但如果我有 1500 种甚至更多方法,情况并非如此。那么是否有任何注释或任何其他方法可以帮助我记录执行时间?

【问题讨论】:

  • JdbcTemplate 的起源在哪里?使用 Aspects 可能是一种选择,但这会产生开销,至少必须牢记这一点。
  • 总之没有。您可以使用@Markus 的建议或查看数据库本身。它可能允许您以编程方式进行
  • 我不确定计算时间的最佳方法是什么,但我制作了一个示例代码,用于计算多个方法的执行时间。希望它有效:stackoverflow.com/questions/27112162/…
  • 哦,有些数据库允许查询日志记录。这将有利于从测量中排除网络和内容。
  • 我的应用程序需要使用任何数据库,所以这不是解决方案

标签: java jdbc jdbctemplate


【解决方案1】:
  1. spring 使用StopWatch 来测量执行时间,apache 也有相同的StopWatch。秒表示例 - https://www.javacodegeeks.com/2012/08/measure-execution-time-in-java-spring.html

  2. 使用 aop 作为执行时间。这里是例子https://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/

    使用 aop 和自定义注解,您可以标记要记录执行时间的方法。

aop - 它的开销并不大,当你使用 @Transactional 时,你也使用 aop,所以你已经有了这个开销


如果您只想记录 dbcTemplate.queryForList() 的执行时间,并且在这对 plase 中,请使用秒表。或者您可以创建自己的 util 方法(包装 dbcTemplate.queryForList()),例如:

public static List<?> queryForListWithLogExecution(String sql){
     List<?> result;
     //measuring elapsed time using Spring StopWatch
        StopWatch watch = new StopWatch();
        watch.start();
        list = jdbcTemplate.queryForList(queryTables); 
        watch.stop();
        logger.info("Total execution time in millis: {0}", watch.getTotalTimeMillis());
        return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2021-01-04
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2010-10-11
    • 2016-01-13
    相关资源
    最近更新 更多