数据库池与PGPoolingDataSource?

Aeg*_*gis 4 java postgresql connection-pooling jdbc

我在使用PGPoolingDataSource类创建数据库池时出现问题,一段时间后,当许多用户正在工作并且没有显示任何错误时,池会关闭

创建池的类的代码是:

public class PgConexion {
    private static PgConexion _instancia = new PgConexion(); // instancia de la clase
    private Configuracion config;
    private PGPoolingDataSource source;

    /**
     * instancia la clase y carga las opciones de configuracion
     */
    public PgConexion() {
        final URL archivo = Constantes.RUTA_CONFIG;

        if(archivo != null){
            config = new Configuracion(archivo);
        }
    }

    /**
     * regresa la instancia del pool de conexiones
     * @return
     */
    public static PgConexion getInstance() {
        return _instancia;
    }

    /**
     * crear la conexion la conexion
     * @return
     * @throws SQLException
     */
    public void crearConexion() throws SQLException{
        source = new PGPoolingDataSource(); 

        // configuracion del pool
        source.setDataSourceName("Logistica");
        source.setServerName(config.get("servidor_sql"));
        source.setPortNumber(Integer.parseInt(config.get("puerto_sql")));
        source.setDatabaseName(config.get("bd_sql"));
        source.setUser(config.get("usuario_sql"));
        source.setPassword(config.get("contrasena_sql"));
        source.setMaxConnections(30);
    }

    /**
     * devuelve la conecion a utilizar
     * @return
     * @throws SQLException
     */
    public Connection nuevaConexion() throws SQLException{
        if(source == null){
            crearConexion();
        }

        // genero la conexion de la lista del pool
        return source.getConnection();
    }

    /**
     * Cierra las conexiones y libera los recursos
     */
    public void cerrarConexion(){
        source.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Fed*_*ina 7

正如JDBC文档所解释的那样,使用PGPoolingDataSource并不是一个好主意.

基本问题是,在达到连接限制时关闭连接之前,将阻止对getConnection()的调用.

您已将值30设置为最大并发连接数,因此如果打算打开31,则会导致线程上的块进行调用.

可能的解决方案:

  • 如果您确定并发连接的实际上限,请增加maxConnections.您还应该检查postgresql.conf中的服务器端连接限制.
  • 使用PGSimpleDataSource.根据应用程序的类型,不使用连接池(因此每次创建连接)都不会成为问题.
  • 如果您确实需要一个连接池,只需在Java级别实现自己的连接.

编辑:您只需运行以下命令即可检查打开的连接数量:

SELECT * FROM pg_stat_activity
Run Code Online (Sandbox Code Playgroud)

每行都是一个连接(包括来自pgAdmin和查询分析器的连接).如果您确定连接数不应该达到上限(但它确实如此),那么您可能遇到某种连接泄漏问题.

  • 你提到如果getConnection()阻塞它是一个问题.应该注意的是,在某些情况下,这可能是_exactly_你想要的行为. (3认同)