在调用 PreparedStatement 时以毫秒为单位设置查询超时,而不是秒?

Mar*_*cus 6 java timeout oracle11g

有没有办法以毫秒而不是秒为单位设置查询超时?java.sql.Statement API 只有秒的方法,但对于我的用例来说,即使是 1 秒也太慢了。

Java API:http : //docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#setQueryTimeout(int)

我正在使用 Oracle 数据库。

ppe*_*rka 3

这相当复杂,但可以工作:

  1. 有一个ExecutorService
  2. 为查询创建 Callable
  3. 将可调用对象提交给 ExecutorService
  4. Future<ResultType>有一个“ get(Long, TimeUnit) ”函数,阻塞直到最多设置的超时 - 它具有可配置的粒度(至少它承诺是这样的......

在几乎 Java 代码中是这样的:

public class MyCallable implements Callable<ResultType> {
  @Override
  public ResultType call() throws Exception {
    //do query, with 1s timeout - that way no thread will be busy for more than 1s
    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

处理请求

ExecutorService threadPool; //initialised somewhere earlier

Future<ResultType> futureResult = threadPool.submit(new MyCallable());
try {
    ResultType result = futureResult.get(100, TimeUnit.MILLISECONDS);
    //results received in time, do the processing here
} catch(TimeoutException e) {
    //request too slow -- handle it
} catch( other exceptions...) { ... }
Run Code Online (Sandbox Code Playgroud)

担忧:

  • 我不知道这意味着多少开销......
  • timeout:我不知道它们将如何处理。
  • 超时的请求将被困在线程池中,直到内部 JDBC 超时 (1s) 开始...
  • 线程池:如果是固定的,可能是瓶颈(参见上面的问题),如果是动态的:可能是开销