关闭的连接在 postgres 中保持空闲

mem*_*und 5 java postgresql spring tomcat connection-pooling

问题:如下创建的关闭连接保留idlepostgres数据库中。

public class MyConnectionHandler() implements AutoCloseable {
    private Connection connection;
    private CopyManager copymanager;

    public void init() {
        //need the following in order to work with postgres COPY api
        connection = ((PooledConnection) dataSource.getConnection()).getConnection();
        copymanager = ((Jdbc4Connection) connection).getCopyAPI();
    }

    @Override
    public void close() {
        connection.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用Tomcat通过集中提供tomcat-jdbc的上下文spring-boot。但这对我的问题不重要:

当我创建连接并在之后关闭它时,该连接在我的数据库中仍然处于空闲状态。select * from pg_stat_activity在那里我仍然可以看到连接,尽管它们明确地关闭了。

这意味着,如果我一天创建 10 个连接,并在一段时间后关闭它们,连接将不断增长。它们永远不会从数据库中删除。

可能是什么问题呢?为什么它们idle即使关闭也保持状态?只有当我关闭我的 java 程序时,连接才会被删除(当然)。

我还尝试在不影响空闲连接的情况下设置以下弹簧属性:

spring.datasource.initial-size=1
spring.datasource.max-idle=1
spring.datasource.min-idle=1
Run Code Online (Sandbox Code Playgroud)