簡體   English   中英

數據源太多打開連接

[英]Datasource too many open connection

我在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

有2個pojnts:

1) Allways在finally塊中關閉連接(和其他DB資源)。 在你的情況下,它可能是:

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 )獲取的連接時,它不會被銷毀 ,而是返回到池中以供將來使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM