我一直在尝试使用 Tomcat 的本机连接池功能来避免我的 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 */}
}
}
每当我在通过dbRead
后调用该函数wait_timeout
时,我都会得到:
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
。
我认为这是因为一些不正确的关闭,但似乎并非如此。