连接关闭方法不起作用,客户端错误太多

Connection close method doesnt work, too many clients error

为什么连接关闭在此代码中不起作用?我尝试通过在 try() 中创建连接来尝试不最终阻止的方法,但是在执行 testDbConnection 几次后,我遇到了太多连接错误,当我尝试通过 pgAdmin 连接到我的数据库时,我看到连接了太多客户端。我该如何解决?为什么关闭连接不起作用?

 private List<DataSource> getDataSources() {
        connectionsNumber = 2;
        List<DataSource> dataSources = new ArrayList<>();
        for (int i = 1; i <= connectionsNumber; i++) {
            Connection connection;
            DataSource dataSource;
            String jdbcUrl = environment.getProperty(String.format("database%d.url", i));
            String user = environment.getProperty(String.format("database%d.username", i));
            String password = environment.getProperty(String.format("database%d.password", i));
            ComboPooledDataSource cpds = new ComboPooledDataSource();
            try {
                cpds.setDriverClass("org.postgresql.Driver");
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
            cpds.setJdbcUrl(jdbcUrl);
            cpds.setUser(user);
            cpds.setPassword(password);
            cpds.setMinPoolSize(3);
            cpds.setAcquireIncrement(5);
            cpds.setMaxPoolSize(20);
            cpds.setMaxIdleTime(1);
            cpds.setMaxConnectionAge(600);
            cpds.setMaxStatements(500);
            dataSource = cpds;
            dataSources.add(dataSource);
        }
        return dataSources;
    }
public void testDbConnection() throws SQLException {
        String query = "select id from users;";
        Statement st = null;
        ResultSet rs = null;
        Connection connection = null;
        List<DataSource> dataSources = getDataSources();
        for (DataSource dataSource : dataSources) {
            try {
                connection = dataSource.getConnection();
                st = connection.createStatement();
                rs = st.executeQuery(query);
                while (rs.next()) {
                    System.out.println("Connection");
                }
            } finally {
                if (st != null) {
                    st.close();
                }
                if (rs != null) {
                    rs.close();
                }
                if (connection != null) {
                    connection.close();
                }
                st = null;
                rs = null;
                connection = null;
            }
        }
    }

在我看来,使用c3p0时,connection.close()并不是真正关闭连接,只是把它放回pool.if你想清理DataSource,你可以使用DataSources.destroy(dataSource);