java - 数据源打开连接过多

标签 java spring jakarta-ee jdbc struct

我在contex.xml中写入:

<Resource name="1_db" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/1_db">
<Resource name="2_db" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/2_db">
<Resource name="3_db" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/3_db">
<Resource name="common" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/common">

Java代码:

public static Connection getDBConnection(String url) 
{
Connection con = null;
    try 
    {
    Context ctx = new InitialContext();
    BasicDataSource ds = (BasicDataSource)tx.lookup("java:comp/env/"+url);
    con = ds.getConnection();
    }catch(Exception e) {}
    return con;
}

之后我打电话:

String url ="common";
LoginDAO ldcom = DAOFactory.getLoginDAO(url);
url ="1_db";
LoginDAO ldcom = DAOFactory.getLoginDAO(url);
StatusDAO ldcom = DAOFactory.getStatusDAO(url);

之后,当我们通过 JProfiler 观察时,它显示了很多打开的连接,尽管我们调用了 con.close()rs.close()st.close()

请提及我们如何以正确的方式使用数据源

最佳答案

有两点:

1)始终在finally block 中关闭连接(和其他数据库资源)。在您的情况下,可能是这样的:

Connection conn = null;
try {
    conn = getDBConnection(xxx);
    // do stuff with the connection
}
// optionally catch any errors that you can handle
finally {
    // close other DB resources that depend on conn, e.g. Statements, ResultSets
    if( conn != null ) try { conn.close(); }
    catch(Exception ignore) {}
}

2) 您看到的打开连接可能是连接池。使用 DriverManager.getConnection() 创建数据库连接是一个昂贵(耗时)的过程。在存在许多并发请求的应用程序服务器环境中,为每个请求创建一个新连接将是性能 killer 。 javax.sql.Datasource 包装了由应用程序服务器管理的连接池。当您 close() 从该池(数据源)获取的连接时,它不会被销毁,而是返回到池中以供将来使用。

关于java - 数据源打开连接过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18868418/

相关文章:

java - 文件不再可读

java - 通过 session 变量存储数据

java - Java中的应用程序服务器和Web服务器有什么区别?

java - spring 拦截器不向@RestController 服务添加 header

java - Java 中多维数组的 ClassCastException

java - 来自 OSGI 的可配置 Java Servlet

java - Spring Boot搭建常用服务的pom结构

java - 如何使用 UiBinder 以声明方式设置 GWT Flextable 第一行(即标题)?

java - HttpClientErrorException getResponseBodyAsString() 无法将字节解析为字符串

java - 是否可以定义多次aop :aspectj-autoproxy element