SQL 我可以为单个查询设置 JDBC 超时吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5397432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:48:47  来源:igfitidea点击:

Can I set a JDBC timeout for a single query?

sqlspringjdbctimeoutjdbctemplate

提问by Shawn D.

I have a web app on Tomcat, which handles DB connection pooling, and using Spring JDBCTemplate for executing queries. It's been requested that I implement a status page which will be monitored by a heartbeat process to determine if everything is healthy with the server.

我在 Tomcat 上有一个 Web 应用程序,它处理数据库连接池,并使用 Spring JDBCTemplate 来执行查询。有人要求我实现一个状态页面,该页面将由心跳进程监视以确定服务器的一切是否正常。

As part of this, I want to do a DB query to determine if the connection to the database is ok. Ideally, since it'd just be a 'select 1 from ', I'd want it to come back fast, within 10 seconds, to indicate a failure if the DB didn't respond in that time.

作为其中的一部分,我想做一个数据库查询来确定与数据库的连接是否正常。理想情况下,因为它只是一个'select 1 from ',我希望它在 10 秒内快速返回,以表明如果数据库在那段时间内没有响应则失败。

However, I don't want to change my connection to time out that quickly for normal requests.

但是,我不想更改我的连接,以便为正常请求快速超时。

Is there a way to set a per-query timeout using either raw JDBC or Spring JDBC wrappers?

有没有办法使用原始 JDBC 或 Spring JDBC 包装器设置每个查询超时?

采纳答案by gkamal

If you are using spring to manage transactions a time out can be specified at the transaction level as well. @Transactional(timeout=10)

如果您使用 spring 来管理事务,则也可以在事务级别指定超时。@Transactional(超时=10)

回答by Tom Micheline

Use setQueryTimeout on the Statement (or PreparedStatement) object.

在 Statement(或 PreparedStatement)对象上使用 setQueryTimeout。