gpt4 book ai didi

java - 如何正确关闭和维护 Java 连接池中的连接

转载 作者:行者123 更新时间:2023-11-30 08:37:35 25 4
gpt4 key购买 nike

几周前,我开始使用 JDBC 建立到我的 mysql 数据库的连接并发送查询。但是,我注意到它减慢了我的 Java 应用程序的速度,所以我开始阅读有关连接池的内容。我决定使用 c3p0 来建立我的连接池。这是我使用的代码:

public static void setUpPool(String id, String pass, String url, String driver) {

cpds = new ComboPooledDataSource();
try {
cpds.setDriverClass(driver);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
cpds.setJdbcUrl(url);
cpds.setUser(id);
cpds.setPassword(pass);

// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(3);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);

}

public static Connection getConnection() {
// The DataSource cpds is now a fully configured and usable pooled
// DataSource
try {
return cpds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

所以我的问题是1. 完成连接后如何正确解除连接? close() 就足够了吗?2. 我应该使用方法 cpds.setCheckoutTimeout(checkoutTimeout) 吗?3. 在连接池中维护连接还有什么需要注意的?

此外,我还收到此警告:警告:池大小配置错误,开始 3 < 分钟 5。使用 5 作为开始。有谁知道这是什么意思吗?

提前致谢。

最佳答案

  1. How do you properly get rid of the connection once you are done with it? Will close() be enough?

是的。使用 try-with-resources 确保每个 Connection 都被 close()ed或在精心编写的 finally 子句中 [精心编写,以便在 close()ing 其他资源时出现异常,例如,不会阻止 Connections 调用 close()]。

  1. Should I use the method cpds.setCheckoutTimeout(checkoutTimeout)?

不,不一定。如果您的应用程序运行良好,则几乎不需要它,因为会立即检查连接。如果您的应用程序泄漏连接(即,您有时无法关闭()它们),那么没有检查超时将导致客户端无限期挂起,这是非常有用的。 checkoutTimeout 在以下情况下最有帮助,由于硬件限制或其他原因,您无法将应用程序配置为始终处理其负载,并且您宁愿告诉客户稍后回来而不是让他们排队。

  1. Is there anything else I should keep in mind when maintaining connections in a connection pool?

是的。您可能应该设置连接测试。这可能就像添加一样简单

cpds.setTestConnectionOnCheckout( true )

到您的 setUpPool(...) 方法。参见 here

关于java - 如何正确关闭和维护 Java 连接池中的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37089507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com