【发布时间】:2019-01-04 06:51:07
【问题描述】:
在我在 Tomcat 上运行的 java web 项目中,2 天后有超过 4000 个休眠连接(我使用 sp_who 命令检查了它们)。在完成数据库工作后,我会关闭每个语句、结果集和连接。我将以下模板用于数据库内容。
try{
this.openConnection();
this.createStatement();
// things ...
this.cleanResources();
}catch (SQLException e){
this.cleanResources();
e.printStackTrace();
}
public void cleanResources() {
try {
if (this.rs != null) {
rs.close();
this.rs = null;
}
if (this.stmt != null) {
stmt.close();
this.stmt = null;
}
if (this.conn != null) this.closeConnection();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (this.conn != null) this.closeConnection();
}
}
public void closeConnection() {
try {
if (this.conn != null)
this.conn.close();
this.isOpen = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void createStatement() {
try {
if (!this.isOpen) this.openConnection();
this.stmt = this.conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void openConnection() {
try {
this.conn = ds.getConnection(); // ds is a javax.sql.DataSource instance
this.isOpen = true;
} catch (Exception e) {
e.printStackTrace();
}
}
每次 sql 代码运行后,具有睡眠状态的行数确实会增加,并且数据库内容会变得非常慢。为什么会发生?完成后如何完全终止连接?真的是睡眠连接让我的 SQL Server 变慢了吗?
这是我的 Tomcat 配置(在 context.xml 中):
maxTotal="20" maxActive="20" maxIdle="20"
【问题讨论】:
-
强烈建议您摆脱该代码并开始使用 try-with-resources。在字段中保留
Statement和ResultSet是不合适的。 --- 但是,如果你坚持这个逻辑,至少你需要把cleanResources()放在一个finally块中。 -
既然我们看不到
openConnection()和closeConnection()方法的作用,我们怎么能说你做对了吗? -
@Andreas 对不起,我错过了那个,现在编辑了。
-
@Andreas 我现在将尝试在 finally 块中进行操作。
-
@Andreas 用 finally 块做这件事没有任何区别,仍然休眠的连接数在增加。
标签: java sql sql-server tomcat