简体   繁体   English

Glassfish不重用JDBC连接

[英]Glassfish does not reuse JDBC Connections

I'm using JDBC connection pooling on a glassfish webserver. 我在glassfish Web服务器上使用JDBC连接池。 I'm injecting the DataSource via this statement: 我通过以下语句注入数据源:

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

The code which I'm using to load data looks something like this: 我用来加载数据的代码如下所示:

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;
}

For some reason glassfish is not reusing database connections, so I'm running out of them very fast. 由于某种原因,glassfish不会重用数据库连接,因此我很快就用光了它们。 Sooner or later i'm always getting this error: 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. Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections.

As I understood the concept of pooling on glassfish: I'm not supposed to close connections after I used them, so something else can reuse the connection when needed. 据我所知,在玻璃鱼上池化的概念是:我不应该在使用连接后关闭连接,因此在需要时其他某些东西可以重用连接。 Glassfish closes connection itself when there is no more demand for the connection. 当不再有连接需求时,Glassfish会自行关闭连接。

Why does my program open a new connection every time? 为什么我的程序每次都打开一个新连接? Do I have to do something with the connection when I'm done? 完成后,我需要对连接做些什么吗?

You still need to call Connection.close() . 您仍然需要调用Connection.close() Your pool will manage your connections, so they won't really be closed, but if you don't "close" them in your code, they won't be returned to the pool. 您的池将管理您的连接,因此它们不会真正被关闭,但是如果您没有在代码中“关闭”它们,它们将不会返回到池中。

Edit : alternatively, use a try-with-resources: https://stackoverflow.com/a/8066594/212224 编辑 :或者,使用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