Java DriverManager getConnection 的连接超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1683949/
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-08-12 21:23:10  来源:igfitidea点击:

Connection timeout for DriverManager getConnection

javaoraclejdbcdatabase-connection

提问by kal

I am trying to connect to DB using the standard JDBC way

我正在尝试使用标准 JDBC 方式连接到数据库

connection = DriverManager.getConnection(url, username, password);

Is there a maximum value of timeout on the connection, how long does a connection live, can I increase the value. I want in cases the connection to be open forever , is it a good idea.

连接超时是否有最大值,连接存活多长时间,我可以增加该值吗?我希望在连接永远打开的情况下,这是一个好主意。

采纳答案by BalusC

The value is usually DB-controlled. You have no control over it using code. It depends on the DB server used. It is usually around 30 minutes up to one hour.

该值通常由 DB 控制。您无法使用代码控制它。这取决于所使用的数据库服务器。通常是大约 30 分钟到一小时。

On the other hand, keeping a Connectionopen forever is a very bad idea. Best practice is to acquire andclose Connection, Statementand ResultSetin the shortestpossible scope to avoid resource leaks and potential application crashes caused by the leaks and timeouts.

另一方面,Connection永远保持开放是一个非常糟糕的主意。最佳实践是获取关闭ConnectionStatementResultSet在尽可能的范围内避免由于泄漏和超时导致的资源泄漏和潜在的应用程序崩溃。

True, connecting the DB is an expensive task. If your application is supposed to run a relatively long time and to connect the DB fairly often, then consider using a connection pool to improve connecting performance. If your application is a webapplication, then take a look in the appserver's documentation, it usually provides a connection pooling facility in flavor of a DataSource. If it is a client application, then look for 3rd party connection pooling libraries which have proven their robustness with years, such as Apache Commons DBCP(commonly used, used in lot appservers), C3P0(known from Hibernate) and Proxool(if you want XA connections).

确实,连接数据库是一项昂贵的任务。如果您的应用程序应该运行相对较长的时间并且经常连接数据库,那么可以考虑使用连接池来提高连接性能。如果您的应用程序是 Web 应用程序,请查看应用程序服务器的文档,它通常提供DataSource. 如果它是一个客户端应用程序,那么寻找 3rd 方连接池库,它们已经证明了多年的健壮性,例如Apache Commons DBCP(常用,用于很多应用程序服务器)、C3P0(从 Hibernate 已知)和Proxool(如果你想要的话) XA 连接)。

Keep in mind, when using a connection pool, you still have to write proper JDBC code, i.o.w. acquire andclose all the resources in the shortest possible scope. The connection pool will on its turn worry about actually closing the connection or just releasing it back to pool for further reuse.

请记住,在使用连接池时,您仍然需要编写适当的 JDBC 代码,以便在尽可能短的范围内获取关闭所有资源。连接池将依次担心实际关闭连接或只是将其释放回池以供进一步重用。

You may get some more insights out of this articlehow to do the JDBC basics the proper way.

您可能会从本文中获得更多关于如何以正确的方式完成 JDBC 基础知识的见解。

Hope this helps and happy coding.

希望这有助于和快乐编码。

回答by Vincent Ramdhanie

You can set the Timeout on the DriverManager like this:

您可以像这样在 DriverManager 上设置超时:

 DriverManager.setLoginTimeout(10);
 Connection c = DriverManager.getConnection(url, username, password);

Which would imply that if the connection cannot open within the given time that it times out.

这意味着如果连接在给定时间内无法打开,则它超时。

In terms of keeping a connection open forever, it is possible if you do not close the connection but it may not be a good idea. Connections should be closed as soon as you are finished with them.

在保持连接永远打开方面,如果您不关闭连接是可能的,但这可能不是一个好主意。连接完成后应立即关闭。

If you want to optimise the opening and closing of connections then you can use a connection pool.

如果要优化连接的打开和关闭,则可以使用连接池。

回答by QQ_QQ

Here is how to do it with Connector/J MYSQL driver:

以下是如何使用 Connector/J MYSQL 驱动程序执行此操作:

String qqq = "jdbc:mysql://localhost/Test?connectTimeout=TIME_IN_MILLIS";
conn = DriverManager.getConnection(qqq, db_user, db_pass);

It worked for me after setLoginTimeout()did nothing.

setLoginTimeout()什么都不做之后它对我有用。

回答by bestro

You can use ExecutorService interface from Java. Below is a sample of what you need to do.

您可以使用 Java 的 ExecutorService 接口。以下是您需要执行的操作的示例。

Future<Boolean> future = executor.submit(YOUR_METHOD);
future.get(TIMEOUT_YOU_NEED, TimeUnit.SECONDS);

回答by Felix

Just reposting a more complete repost of a comment from user flamming_python as answer because it worked for me:

只是重新发布来自用户 flamming_python 的评论的更完整的重新发布作为答案,因为它对我有用:

dbConnectionString = "jdbc:mysql://"+dbHost+":"+dbPort+"/"+dbTable+"?user="+dbUser+"&password="+dbPassword;
Properties properties = new Properties();
properties.put("connectTimeout", "2000");
dbConnect = DriverManager.getConnection(dbConnectionString, properties);

Original comment:
"LoL @ your threads - you can do it quite simply by creating a Properties object prop, then prop.put("connectTimeout", "2000") (where the "2000" is the timeout in ms), and then pass your prop object to the DriverManager.getConnection() method along with your url"

原始评论:
“大声笑@你的线程 - 你可以很简单地通过创建一个 Properties 对象 prop,然后 prop.put("connectTimeout", "2000") (其中“2000”是以毫秒为单位的超时),然后将您的道具对象与您的网址一起传递给 DriverManager.getConnection() 方法”

回答by Fidel

As bestro suggested, it's possible to use a future with an associated timeout. For example:

正如 bestro 所建议的那样,可以使用具有关联超时的未来。例如:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Connection> future = executor.submit(new Callable<Connection>() {

    @Override
    public Connection call() throws Exception {
        Connection con = DriverManager.getConnection(url, username, password);
        return con;
    }
});

Connection con = null;
try {
    con = future.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
    Logger.getLogger(Scratch.class.getName()).log(Level.SEVERE, null, ex);
}
executor.shutdownNow();

if (con == null) {
    System.out.println("Could not establish connection");
} else {
    System.out.println("Connection established!");
}