连接池:关闭或不关闭连接?

时间:2016-11-29 10:58:49

标签: java database-connection connection-pooling

我在JSF Java应用程序中使用dbcp的BasicDataSource。由于基本约定是在使用它之后关闭连接,我在catch中这样做 - 最后在我的代码中。但是,应用程序因错误而停止运行,

java.sql.SQLException: Connection is null.
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.checkOpen(DelegatingConnection.java:611)
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.createStatement(DelegatingConnection.java:258)

所以我决定不关闭我的联系;我的代码几乎运行正常,但后来常常因此错误停止:

Caused by: org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections

以下是我的连接配置:

public class StageDB {
    public StageDB() {}
    public static Connection getConnection() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(JDBC_DRIVER);
        ds.setUsername(USER);
        ds.setPassword(PASS);
        ds.setUrl(DB_URL);
        ds.setTimeBetweenEvictionRunsMillis(20*1000);
        ds.setMinIdle(0);
        ds.setMaxIdle(10);
        ds.setMaxOpenPreparedStatements(100);
        conn = ds.getConnection();
        return conn;
    }
}

我应该提一下,我尝试过使用这些设置,并使用默认设置,但结果相同。我能做错什么?

1 个答案:

答案 0 :(得分:0)

在我意识到我做错了之后,我找到了解决方法。所以这就是我能够提出的,与我的设计方法完美配合。

//1. Create pooled connections datasource class using the Singleton.

/***************************
* This is the pooled datasource class
****************************/
public class PrimaryDS {
    private PrimaryDS primaryDS;

    public PrimaryDS() {
        ds = new BasicDataSource();
        ds.setDriverClassName(JDBC_DRIVER);
        ds.setUsername(USER);
        ds.setPassword(PASS);
        ds.setUrl(DB_URL);
    }

    public static PrimaryDS getInstance() {
        primaryDS = primaryDS == null ? new PrimaryDS() : primaryDS;
        return primaryDS;
    }

    public BasicDataSource getDataSource() {
        return ds;
    }

    public void setDataSource(BasicDataSource ds) {
        this.ds = ds;
    }
}

//2. DAOs make call to the datasource. Initialize DS in the DAO's constructor.

/***************************
* This is in the DAO's constructor
****************************/
ds = PrimaryDS.getInstance().getDataSource();

//3. DAOs have the database manupulation methods. In each of these methods, 
//create connection object from ds, and ensure it's closed in the catch - finally.

/***************************
* This is inside one of the DAO methods
****************************/
try {
    conn = ds.getConnection();
    stmt = null;
    rs = null;
    PreparedStatement pstmt = conn.prepareStatement(ACTIVE_ACCOUNTS_SQL);
    pstmt.setByte(1,status);
    ResultSet rs = pstmt.executeQuery();
    // TODO loop through rs
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    try {
        if(rs != null) rs.close();
        if(stmt != null) stmt.close();
        if(conn != null) conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}