【问题标题】:Timing out DriverManager.getConnection()?DriverManager.getConnection() 超时?
【发布时间】:2015-03-24 13:39:16
【问题描述】:

我正在使用 Java 和 mysql 作为数据库,但遇到了一个奇怪的问题: 我的一个客户的连接非常不稳定,有时丢包率可能很高。好吧,我知道这不是软件的错,但我去那里测试,当程序调用“DriverManager.getConnection()”并且网络连接变得不稳定时,该行会锁定应用程序(或给定线程)几分钟.我当然添加了一些逻辑来使用另一个数据源在本地缓存数据,然后尽可能保存到网络主机,但是,我不能经常让程序挂起超过 10 秒(而且这种方法似乎没有任何超时规范)。 所以,我想出了一个这样的解决方法:

public class CFGBanco implements Serializable {
    public String driver = "com.mysql.jdbc.Driver";
    public String host;
    public String url = "";
    public String proto = "jdbc:mysql://";
    public String database;
    public String user;
    public String password;
}

private static java.sql.Connection Connect(HostConfig dataHost) throws java.sql.SQLException, ClassNotFoundException
    {
        dataHost.url = dataHost.proto+dataHost.host;
        if(dataHost.database != null && !dataHost.database.equals("")) dataHost.url += "/"+dataHost.database;
        java.lang.Class.forName(dataHost.driver);
            ArrayList<Object> lh = new ArrayList<>();
            lh.add(0, null);
            Thread ConThread = new Thread(()-> {
                try {
                    lh.add(0, java.sql.DriverManager.getConnection(
                        dataHost.url, dataHost.user, dataHost.password));
                } catch(Exception x ) {
                    System.out.println(x.getMessage());
                }
            }, "ConnThread-"+SessId);
            ConThread.start();
            Thread TimeoutThread = new Thread(() -> {
                int c = 0;
                int delay = 100;
                try {
                    try {
                        do {
                            try {
                                if(t.isAlive())
                                    Thread.sleep(delay);
                                else
                                    break;
                            } catch(Exception x) {}
                        } while((c+=delay) < 10000);
                    } catch(Exception x){}
                } finally { 
                    try {
                        t.stop();
                    } catch(Exception x){}
                }
            }, "ConTimeout-"+SessId);
            TimeoutThread.start();
            try {
                ConThread.join();
            } catch(Exception x) {}
            if(lh.get(0) == null)
                throw new SQLException();
        return (Connection) lh.get(0);
    }

我从另一个线程调用 getConnection,然后创建一个辅助“超时”线程来观察它,然后将调用线程加入 ConThread。 确实,我得到的结果接近预期,但这让我想知道: 有一个更好的方法吗?创建 2 个线程是否会占用大量系统资源,足以使这种方法不切实际?

【问题讨论】:

    标签: java mysql multithreading


    【解决方案1】:

    您需要连接池。汇集连接并重用它,而不是每次都重新创建。一个这样的数据库连接池库是DBCP by Apache

    它会处理连接断开等情况。您可以有验证查询,它会在从池中借用连接之前查询数据库,一旦验证成功,它将触发您的实际查询。

    【讨论】:

    • 真的很好,你。
    猜你喜欢
    • 2011-06-18
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多