解决 Closing expired connections 的代码
一种解决 "Closing expired connections" 的方法是使用连接池来管理连接。连接池可以在需要时提供可用的连接,而且可以在一段时间内自动关闭不活跃的连接。
以下是一个示例代码,使用连接池解决 "Closing expired connections" 问题:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.dbcp2.BasicDataSource;
public class ConnectionPoolExample {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final int MAX_TOTAL_CONNECTIONS = 10;
private static final int MAX_IDLE_CONNECTIONS = 5;
private static final int MIN_IDLE_CONNECTIONS = 1;
private static final long MAX_CONNECTION_WAIT_TIME = TimeUnit.SECONDS.toMillis(10);
public static void main(String[] args) {
// Create a connection pool using BasicDataSource
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(JDBC_URL);
dataSource.setUsername(USERNAME);
dataSource.setPassword(PASSWORD);
dataSource.setMaxTotal(MAX_TOTAL_CONNECTIONS);
dataSource.setMaxIdle(MAX_IDLE_CONNECTIONS);
dataSource.setMinIdle(MIN_IDLE_CONNECTIONS);
dataSource.setMaxWaitMillis(MAX_CONNECTION_WAIT_TIME);
// Get a connection from the pool
try (Connection connection = dataSource.getConnection()) {
// Use the connection for database operations
// ...
// Connection will be automatically closed when try block is exited
} catch (SQLException e) {
e.printStackTrace();
}
// Close the connection pool when no longer needed
dataSource.close();
}
}
在上面的示例代码中,我们使用了 Apache Commons DBCP2 的 BasicDataSource 类来创建连接池。我们设置了最大总连接数、最大空闲连接数、最小空闲连接数和最大连接等待时间等参数。然后,我们可以通过调用 getConnection() 方法从连接池中获取一个连接,在使用完之后,连接会自动返回到连接池中并可供其他代码使用。最后,当不再需要连接池时,我们可以调用 close() 方法来关闭连接池。
这样,我们可以避免手动关闭连接的问题,并且连接池会自动关闭不活跃的连接,从而解决 "Closing expired connections" 的问题。
原文地址: https://www.cveoy.top/t/topic/i4cw 著作权归作者所有。请勿转载和采集!