在我们正在处理的应用程序中,用户可以通过在文本字段中输入任意JDBC连接URL来连接到外部RDBMS。我们的一位客户报告称,当他意外地尝试使用MySQL JDBC URL连接到Microsoft SQL Server时,我们的应用程序服务器冻结(无限期)为0%CPU。
以下Java代码段说明了这种情况:
public static void main(String[] args){
// note: the application running on localhost:1433 is ACTUALLY
// an MS SQL Server instance!
String jdbcUrl = "jdbc:mysql://localhost:1433/my-db";
// enable JDBC Driver Manager logging
DriverManager.setLogWriter(new PrintWriter(System.err));
// set a timeout of 5 seconds for connecting (which is blissfully ignored!)
DriverManager.setLoginTimeout(5);
// open the connection (which should fail, but freezes instead)
try (Connection c = DriverManager.getConnection(jdbcUrl)){
System.out.println("This should never be reached due to wrong JDBC URL.");
}catch(Exception e){
System.out.println("This is expected (but never printed).");
}
System.out.println("This is never printed either.");
}
要运行代码段
问题:
我尝试了其他几个JDBC驱动程序(MySQL,DB2,Oracle ......),他们都优雅地处理了这个问题,只有MariaDB JDBC驱动程序冻结了JVM。
答案 0 :(得分:0)
以下是我为解决此问题所做的工作。诀窍是在连接中添加socketTimeout
。要在问题中修复程序,只需将JDBC URL修改为:
jdbc:mysql://localhost:1433/my-db?socketTimeout=2000
This answer相关问题是我需要的提示。
答案 1 :(得分:0)
答案1:是的,这是一个错误。他们错过了在执行mariadb jdbc驱动程序时使用登录超时的操作。
答案2:我通过使用包装getConnection方法的任务来解决。如果尚未完成定义的登录时间,则该任务将停止。这是我的实现。
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import org.mariadb.jdbc.util.DefaultOptions;
public class ConnectionTest {
private static final String CONNECTION_STRING = "jdbc:mariadb://localhost:3306/test";
private static final String USER = "root";
private static final String PW = "";
private static final int LOGIN_TIMEOUT_SEC = 2;
public static void main(String[] args) throws Exception {
var test = new ConnectionTest();
Connection connection = test.getConnection();
if(connection != null && connection.isValid(LOGIN_TIMEOUT_SEC)) {
System.out.println("Connected!");
}
}
private Connection getConnection() throws Exception {
ConnEstablishSync sync = new ConnEstablishSync();
Properties conProps = new Properties();
conProps.setProperty(DefaultOptions.USER.getOptionName(), USER);
conProps.setProperty(DefaultOptions.PASSWORD.getOptionName(), PW);
FutureTask<Connection> task = new FutureTask<>(() -> {
Connection c = DriverManager.getConnection(CONNECTION_STRING, conProps);
if(sync.canceled && c != null) {
c.close();
c = null;
}
return c;
});
Connection connection = null;
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.submit(task);
connection = task.get(LOGIN_TIMEOUT_SEC, TimeUnit.SECONDS);
} finally {
sync.canceled = true;
task.cancel(true);
executor.shutdown();
}
return connection;
}
private static class ConnEstablishSync {
private volatile boolean canceled = false;
}
}