gpt4 book ai didi

java - 连接关闭不会关闭Tomcat中的连接

转载 作者:行者123 更新时间:2023-11-28 22:47:56 32 4
gpt4 key购买 nike

在我运行在 Tomcat 上的 java web 项目中,2 天后有超过 4000 个 hibernate 连接(我用 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 代码运行后,处于 hibernate 状态的行数确实会增加,并且数据库内容会变得非常慢。为什么会这样?完成连接后如何完全终止连接?真的是 hibernate 连接让我的 SQL Server 变慢了吗?

这是我的 Tomcat 配置(在 context.xml 中):

maxTotal="20" maxActive="20" maxIdle="20"

最佳答案

您用于清理连接的代码/模式存在缺陷:

try {
this.openConnection();
this.createStatement();

// things ...

this.cleanResources();
} catch (SQLException e){
this.cleanResources();
e.printStackTrace();
}

如果“事物”抛出一些不是 SQLException 或子类的异常,这不会关闭连接。

如果应该是:

try {
this.openConnection();
this.createStatement();

// things ...

this.cleanResources();
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.cleanResources();
}

然后这个:

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();
}
}

如果 rs.close()stmt.close() 抛出异常,则连接不会关闭。

应该是这样的:

public void cleanResources() {
try {
if (this.rs != null) {
rs.close();
this.rs = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (this.stmt != null) {
stmt.close();
this.stmt = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (this.conn != null) this.closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
}

在某些情况下,这些缺陷中的任何一个都可能导致数据库连接泄漏。

另一种可能性是您的代码中某处没有遵循您的(有缺陷的)模式。

我认为您需要继续阅读:

  • Java 7+“尝试资源”支持
  • Java 1.0+“尝试……最后”。

还值得注意的是,以下做法是不好的做法:

  • 捕获Exception ...在大多数情况下
  • 压缩异常(即捕获并静默继续)......在大多数情况下
  • 在整个代码中分散对 printStackTrace 的调用。

关于java - 连接关闭不会关闭Tomcat中的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51552992/

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