代码之家  ›  专栏  ›  技术社区  ›  Martin Häusler

JDBC驱动程序忽略连接超时吗?

  •  1
  • Martin Häusler  · 技术社区  · 7 年前

    在我们正在开发的应用程序中,用户可以通过在文本字段中输入任意jdbc连接url来连接到外部rdbms。我们的一个客户报告说,当他不小心试图用mysql jdbc url连接到一个microsoft sql服务器时,我们的应用服务器冻结(不确定)在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.");
    }
    

    运行代码段:

    • 在localhost:1433上运行一个SQL Server实例(内容无关紧要)
    • 使用Mariadb JDBC驱动程序版本2.2.5。(最新)在你的课堂上。

    问题:

    • 1)这可能是mariadb jdbc驱动程序中的错误吗?谷歌搜索没有透露这方面的内容。
    • 2)我应该如何解决这个问题?当用户意外插入一个无效的JDBC URL时,我不希望我的服务器冻结。

    我尝试了其他几个JDBC驱动程序(MySQL、DB2、Oracle…),它们都优雅地处理这个问题,只有MialADB JDBC驱动程序冻结JVM。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Martin Häusler    7 年前

    以下是我为解决这个问题所做的。诀窍是添加 socketTimeout 连接。要修复问题中的程序,只需将jdbc url修改为:

    jdbc:mysql://localhost:1433/my-db?socketTimeout=2000

    This answer 一个相关的问题是我需要的暗示。