【问题标题】:Glassfish does not reuse JDBC ConnectionsGlassfish 不重用 JDBC 连接
【发布时间】:2015-10-12 02:43:17
【问题描述】:

我在 glassfish 网络服务器上使用 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.

根据我对 glassfish 池化概念的理解:我不应该在使用连接后关闭连接,因此其他东西可以在需要时重用连接。当不再需要连接时,Glassfish 会自行关闭连接。

为什么我的程序每次都打开一个新连接?完成后我是否必须对连接做一些事情?

【问题讨论】:

    标签: java jdbc glassfish pooling


    【解决方案1】:

    您仍然需要致电Connection.close()。您的池将管理您的连接,因此它们不会真正关闭,但如果您不在代码中“关闭”它们,它们将不会返回到池中。

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

    【讨论】:

    • try-with-resources 完成后是否会自动关闭连接?当抛出异常并且必须中止时,它是否也会关闭资源?
    • 附加问题:我试图阅读它,显然有一个东西叫做抑制异常,我真的没有得到。 try-with-resources 中是否仍然抛出异常?
    【解决方案2】:
    Connection con = db.getConnection();
    try {
        PreparedStatement ps = con.prepareStatement("Select * from stufftable");
        ...
    } finally {
        // this returns the connection to the pool
        con.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 2013-07-13
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2015-11-16
      相关资源
      最近更新 更多