I've been trying to Tomcat's native conncetion pooling features to avoid connection timeouts in my Java web project, but it seems I'm still out of luck.
I've put mysql-connector-java-5.1.23-bin.jar
in the WEB-INF/lib
folder, created a META-INF/context.xml
like this:
<?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>
Here's what I do:
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 */}
}
}
Whenever I call the function dbRead
after the wait_timeout
has passed, I get:
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.
with a SQL state 08S01
.
I thought it was because of some uncorrect closings, but it doesn't seem the case.