超时后终止长 运行 查询

Kill the long running queries after timeout

我们的应用程序包含作为入口点的 apache 网络服务器,并且应用程序将 运行 在另一台服务器上。因此,在 apache 中,我们将超时配置为 40 秒,但在应用程序中,某些查询需要更多时间来获取超过 40 秒的记录,因此 apache 抛出 5xx 错误。但是在我们从 apache 网络服务器得到响应后,查询正在从数据库中获取记录。

如何在 40 秒(即 apache 超时)后终止该查询(或事务)?

提前致谢。

您可以使用 Spring 的 AsyncTaskExecutor

Extended interface for asynchronous TaskExecutor implementations, offering an overloaded execute(Runnable, long) variant with a start timeout parameter as well support for Callable. Note: The Executors class includes a set of methods that can convert some other common closure-like objects, for example, PrivilegedAction to Callable before executing them.

停止数据库查询的一种方法是Statement.cancel()

这取决于您的环境。您可以在 JTA 中设置事务超时,或者您可以使用数据库特定的功能,例如postgres 会话参数:statement_timeout

如果您有一个长查询,JTA 超时不是很有用,因为 JTA 不能中断 JDBC 调用。

编辑

JDBC API现在有语句超时:java.sql.Statement.setQueryTimeout(int timeout),但并非所有驱动程序都支持它。

我们可以使用 Hibernate 事务管理器的 setDafaultTimeout 方法来指定超时时间。

      HibernateTransactionManager transactionManager = new HibernateTransactionManager();
      transactionManager.setDefaultTimeout(int timeoutinSecs);

那么hibernate会抛出事务超时过期异常。根据我们的要求,我们可以处理该异常。

您可以很好地实现自己的查询处理程序,并根据需要终止查询。