数据源太多打开连接

时间:2013-09-18 09:22:49

标签: java spring java-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()

请提及我们如何以正确的方式使用Datasource

1 个答案:

答案 0 :(得分:2)

有2个pojnts:

1)始终关闭finally块中的连接(以及其他数据库资源)。在您的情况下,它可能是:

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()创建数据库连接是一个昂贵(耗时)的过程。在存在许多并发请求的应用程序服务器环境中,为每个请求创建新连接将是性能杀手。 javax.sql.Datasource包装应用程序服务器管理的连接池。当您close()从该池(Datasource)获取连接时,它不会被销毁,而是返回到池中以供将来使用。< / p>

相关问题