CommunicationsException:最后一个数据包在 xxx 毫秒前成功发送到服务器

CommunicationsException: The last packet sent successfully to the server xxx milliseconds ago

我对 Java 中的 MySQL/JDBC 个连接有疑问。

我编写了一个成功与数据库通信的应用程序,但我最近发现的问题是我的数据库连接正在断开,我需要该应用程序始终与数据库建立连接。

这是我遇到的错误的一小段:

com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was 89,225,584 milliseconds ago. The last packet sent successfully to the server was 89,225,584 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)

这也是我的 DBConnections 的构造函数的一个片段 class:

private final String url = "jdbc:mysql://localhost:3306/", database.....;
private Connection connection;
    

public DBConnector(){
        try {
          //  Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url+database, username, password);
        } catch (Exception ex) {
            System.out.println("Error: " + ex);
        }
    }

在错误部分,我注意到它告诉我添加 autoReconnect=true,我想知道;如果我这样构建连接 class,我的连接还会保持更长时间吗:

connection = DriverManager.getConnection(url+database+"?autoReconnect=true", username, password);

如果没有,我还能做些什么来确保我的连接不会断开?

我建议使用连接池(Apache DBCP 或 HikariCP - 最后一个是目前市场上所有解决方案中性能最好的),在从池中借用之前配置测试连接。根据图书馆的不同,应该有一个选项,如 setTestOnBorrow(true).

在实际应用中,您应该始终使用连接池而不是手动处理连接。