繁体   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