Java 如何在 MySQL JDBC 驱动程序上设置连接超时?

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

How to set a connection timeout on the MySQL JDBC driver?

javamysqljdbctimeoutconnection-timeout

提问by Edy Bourne

I'm seeing the JDBC MySQL driver consistently fail connection attempts to a stopped MySQL after 10 seconds, but I'd like to change that timeout.

我看到 JDBC MySQL 驱动程序在 10 秒后始​​终无法连接到已停止的 MySQL,但我想更改该超时。

I tried adding ?connectTimeout=2000&socketTimeout=2000 to the connection URI, but that didn't make a difference.

我尝试将 ?connectTimeout=2000&socketTimeout=2000 添加到连接 URI,但这并没有什么区别。

Is there a way to customize how long it takes for the Driver to return a timeout while connecting to MySQL?

有没有办法自定义驱动程序在连接到 MySQL 时返回超时所需的时间?

Thanks!

谢谢!

Eduard

爱德华

采纳答案by Salah

You can change the default value in MySQL configuration file (connect-timeout option in mysqld section) -

您可以更改 MySQL 配置文件中的默认值(mysqld 部分中的连接超时选项)-

[mysqld]
connect-timeout=100

If this file is not accessible for you, then you can set this value using this statement -

如果您无法访问此文件,则可以使用此语句设置此值 -

SET GLOBAL connect_timeout=100;

回答by ravibagul91

You can set the connection timeout using this:

您可以使用以下方法设置连接超时:

con.query('SET GLOBAL connect_timeout=2000')
con.query('SET GLOBAL wait_timeout=2000')
con.query('SET GLOBAL interactive_timeout=2000')

For more help see MySqlConnection

有关更多帮助,请参阅MySqlConnection

回答by Adrian Baker

I tried adding ?connectTimeout=2000&socketTimeout=2000 to the connection URI, but that didn't make a difference.

我尝试将 ?connectTimeout=2000&socketTimeout=2000 添加到连接 URI,但这并没有什么区别。

This is exactly how it's configured, eg

这正是它的配置方式,例如

jdbc:mysql://aaa.bbb.ccc.rds.amazonaws.com:1234/hello?connectTimeout=5000&socketTimeout=30000

See https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html.

请参阅https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html

回答by Johan Le Roux

Adding this before you call getConnection.

在调用 getConnection 之前添加它。

...
DriverManager.setLoginTimeout(2);
DriverManager.getConnection(connectString);
...

Worked in my case.

在我的情况下工作。