连接池抽象类

时间:2015-04-23 13:10:18

标签: java database connection-pooling

我正在为连接池实现一个抽象类。目标是继承此类以管理程序中使用的每个数据库的连接池并封装常见查询。我有几个疑问:

  1. 从查询池获取连接并在执行查询后关闭它是否有效,或者更好地在另一个级别实现它以保持打开连接? (方法selecSimple)。我用100000个查询进行了测试:

    • 为每个查询从池中获取和关闭连接的时间为86440毫秒。

    • 并且81107毫秒只从池中获取一个连接并使用它来执行所有查询,所以我认为没有这么大的差异。

  2. 我将ResultSet数据传递给另一个容器,以便尽快释放连接,即使我必须重复数据两次,一次将数据放入新容器中,另一次将数据放入新容器中用过的。你认为,这是一个好习惯,还是应该更好地在另一个层面实现查询?

  3. public abstract class ConnectionPool implements IConnectionPool {
    /**  Connection Pool dataSource */
    private DataSource datasource;
    
    @Override
    public Connection getConnection() throws SQLException {
        return datasource.getConnection();
    }
    
    @Override
    public void closeConnectionPool() {
        datasource.close();
    }
    
    @Override
    public void setConnectionPool (String url, String driver, String user, String pass) throws SQLException {
        // Using tomcat connection pool but it could be other
        PoolProperties pool = new PoolProperties();
        pool.setUrl(url);
        // Set pool configuration
        ...    
        datasource = new DataSource();
        datasource.setPoolProperties(pool);
    }
    
    // QUERIES  
    @Override
    public List<Map<String, Object>> selectSimple (String query, String [] params) throws SQLException {        
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection con = null;
        List<Map<String, Object>> results = null;
        // Set the preparedstatement
        ...     
        try {
            con = getConnection();
            ps = con.prepareStatement(selectString);
            rs = ps.executeQuery(selectString);
            results = resultSetToArrayList(rs);
    
            rs.close();
            ps.close();
            con.close();
        } catch (SQLException e) {
            throw new SQLException ();
        } finally {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
            if (con != null) ps.close();
        }
        return results;
    }
    
    /** Transforms ResultSet into a List of Maps */
    private List<Map<String, Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
        ...
        return list;
    }
    

    那么,当应用程序完成时,是否足以关闭数据源以释放资源?(closeConnectionPool方法)。 我非常感谢任何帮助。提前谢谢。

0 个答案:

没有答案
相关问题