简体   繁体   English

带有超时的JDBC postgres查询

[英]JDBC postgres query with a timeout

Unfortunately setTimeout is not implemented for JDBC/postgres. 不幸的是,setTimeout没有为JDBC / postgres实现。 Is there some way I can simulate or workaround this? 有什么方法可以模拟或解决此问题? Functionally I want to execute the query and the then break if it takes longer than N seconds 从功能上讲,我想执行查询,然后如果花费的时间超过N秒,则将其中断

The "statement_timeout" looks like what you want. “ statement_timeout”看起来像您想要的。

SET statement_timeout TO 1000; -- for a second
<your_query_here>;
RESET statement_timeout; -- reset

One way might be to try running the query in a Timer class. 一种方法是尝试在Timer类中运行查询。 Throw an exception if the Timer ends without a value returned. 如果计时器结束而没有返回值,则引发异常。

Hibernate and JDO supply such a construct. HibernateJDO提供了这样的构造。 Maybe they'd be good alternatives for you. 也许它们将是您的理想选择。

What if you were to use c3p0 for your dataSource? 如果要对数据源使用c3p0怎么办? It has lots of configurable options, and for cranky databases and networks, for example, acquireRetryAttempts, acquireRetryDelay, and breakAfterAcquireFailure. 它具有许多可配置的选项,对于怪异的数据库和网络,例如,acquireRetryAttempts,acquireRetryDelay和breakAfterAcquireFailure。

Using the LOCAL keyword limits the scope of the statement_timeout to the current transaction. 使用LOCAL关键字将statement_timeout的范围限制为当前事务。 That way, if anything goes wrong (eg it times out) the timeout gets reset. 这样,如果发生任何错误(例如超时),超时将重置。

BEGIN TRANSACTION;
SET LOCAL statement_timeout TO 1000;    -- one-second timeout
SELECT COUNT(*) FROM really_huge_table; -- your slow query
ROLLBACK;                               -- reset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM