簡體   English   中英

Glassfish不重用JDBC連接

[英]Glassfish does not reuse JDBC Connections

我在glassfish Web服務器上使用JDBC連接池。 我通過以下語句注入數據源:

@Resource(lookup="database")
DataSource db;

我用來加載數據的代碼如下所示:

public ArrayList<Stuff> loadStuff()throws SQLException{
    PreparedStatement ps = db.getConnection().prepareStatement("Select * from stufftable");
    ResultSet rs = ps.executeQuery();
    ArrayList<Stuff> stuffs= new ArrayList<Stuff>();
    if(rs.next()){
        Stuff stuff = new Stuff();
        stuff.setString1(rs.getString("string1"));
        stuff.setString1(rs.getString("string1"));
        stuffs.add(stuff );
    }
    return stuffs;
}

由於某種原因,glassfish不會重用數據庫連接,因此我很快就用光了它們。 遲早我總是會收到此錯誤: Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections. Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections.

據我所知,在玻璃魚上池化的概念是:我不應該在使用連接后關閉連接,因此在需要時其他某些東西可以重用連接。 當不再有連接需求時,Glassfish會自行關閉連接。

為什么我的程序每次都打開一個新連接? 完成后,我需要對連接做些什么嗎?

您仍然需要調用Connection.close() 您的池將管理您的連接,因此它們不會真正被關閉,但是如果您沒有在代碼中“關閉”它們,它們將不會返回到池中。

編輯 :或者,使用try-with-resources: https : //stackoverflow.com/a/8066594/212224

Connection con = db.getConnection();
try {
    PreparedStatement ps = con.prepareStatement("Select * from stufftable");
    ...
} finally {
    // this returns the connection to the pool
    con.close();
}

暫無
暫無

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

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