gpt4 book ai didi

Java和MySQL连接池: avoid timeouts

转载 作者:行者123 更新时间:2023-11-29 00:25:30 28 4
gpt4 key购买 nike

<分区>

我一直在尝试使用 Tomcat 的 native 连接池功能来避免我的 Java Web 项目中的连接超时,但似乎我仍然不走运。

我已经将 mysql-connector-java-5.1.23-bin.jar 放在了 WEB-INF/lib 文件夹中,创建了一个 META- INF/context.xml 像这样:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/TheDatabase" auth="Container"
type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
maxActive="100" maxIdle="30" maxWait="1000"
poolPreparedStatements="true" maxOpenPreparedStatements="100"
username="user" password="pass"
url="jdbc:mysql://localhost:3306/my_database"/>
</Context>

这是我的做法:

public static init() {
...
sqlDataSource = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/TheDatabase");
...
}

public static ArrayList<ResultSet> dbRead() {
Connection conn = sqlDataSource.getConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM the_table");
...
res.close();

return out;
} catch (SQLException e) {
// Logging stuff
return null;
} finally {
if (stmt != null)
try {if (!stmt.isClosed()) stmt.close();}
catch (SQLException e) {/* Logging stuff */}
if (conn != null)
try {if (!conn.isClosed()) conn.close();}
catch (SQLException e) {/* Logging stuff */}
}
}

每当我在 wait_timeout 过去后调用函数 dbRead 时,我得到:

Communications link failure

The last packet successfully received from the server was 1.818.697 milliseconds
ago. The last packet sent successfully to the server was 0 milliseconds ago.

具有 SQL 状态 08S01

我以为是因为一些不正确的关闭,但事实并非如此。

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