Java 在数据库之间循环会导致泄漏的连接无法关闭,从而导致';连接太多';

Java 在数据库之间循环会导致泄漏的连接无法关闭,从而导致';连接太多';,java,mysql,jdbc,c3p0,Java,Mysql,Jdbc,C3p0,我目前正在研究在mysql数据库之间切换的东西,以便检查某些更改。但是,当使用下面的switchSource方法切换数据库和主机时,会导致成功切换,但连接保持打开状态,并且似乎没有关闭或遵守setMaxIdleTime设置 因此,每次连接到数据库主机和数据库时,它都会创建更多的连接,这些连接在每次重新连接时不断累积,直到数据库主机停止接受连接并返回“连接过多”错误 我想知道如何最好地关闭这些连接 运行查询时,它们处于try-catch(例如,try(Connection conn=DataSou

我目前正在研究在mysql数据库之间切换的东西,以便检查某些更改。但是,当使用下面的
switchSource
方法切换数据库和主机时,会导致成功切换,但连接保持打开状态,并且似乎没有关闭或遵守
setMaxIdleTime
设置

因此,每次连接到数据库主机和数据库时,它都会创建更多的连接,这些连接在每次重新连接时不断累积,直到数据库主机停止接受连接并返回“连接过多”错误


我想知道如何最好地关闭这些连接

运行查询时,它们处于try-catch(例如,
try(Connection conn=DataSource.getInstance().getConnection())
)中,并且语句也在捕获之前关闭。因此,再加上
setMaxIdleTime
,我不确定为什么连接没有被关闭

如果有人能解释一下,我真的很感激。谢谢你的阅读

package com.example.database;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import com.example.base.ShardNode;
import com.example.manage.ShardManager;
import com.mchange.v2.c3p0.ComboPooledDataSource;  

import static com.example.manage.ShardManager.shardNodeList;


// see https://www.javatips.net/blog/c3p0-connection-pooling-example
public class DataSource {

    private static DataSource datasource;
    private ComboPooledDataSource cpds;
    private static int currentShardId = -1;
    private static ShardNode currentShardNode;
    private static boolean dbIsNotSpecified;
    private static boolean clearConnections = false;

    private static String GetDatabaseUrlAndDB(ShardNode selectedShard) {
        System.out.println(selectedShard.getFullUrl() + ShardManager.getDatabaseName(currentShardId));

        if (dbIsNotSpecified) {
          return selectedShard.getFullUrl();
        }

        return selectedShard.getFullUrl() + ShardManager.getDatabaseName(currentShardId);
    }

    private DataSource() throws PropertyVetoException {

        this.cpds = new ComboPooledDataSource();
        this.cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
        this.cpds.setJdbcUrl(GetDatabaseUrlAndDB(currentShardNode));
        this.cpds.setUser(currentShardNode.getUsername());
        this.cpds.setPassword(currentShardNode.getPassword());

        // the settings below are optional -- c3p0 can work with defaults
//        cpds.setInitialPoolSize(5);
//        cpds.setMinPoolSize(5);
//        cpds.setAcquireIncrement(5);
//        cpds.setMaxPoolSize(100);
//        cpds.setMaxStatements(100);

        /*
         * Set this low to prevent connections from hanging around after the worker has left
         * Otherwise it results in too many connections being made on a single node and the server
         * starts rejecting new connections.
         */
//        cpds.setMaxIdleTime(1);
    }

    /* Refreshes the datasource to use a new id */
    public static void switchSource(int shardId, boolean dbNotSpecified) throws PropertyVetoException {
        // TODO continue work here. Pass id to data source and pull through credentials
        currentShardId = shardId;
        dbIsNotSpecified = dbNotSpecified;

        for(ShardNode CurrentShard: shardNodeList) {
            if ((shardId >= CurrentShard.getStartingShard())
                    && (shardId <= CurrentShard.getEndingShard())) {
                currentShardNode = CurrentShard;
                datasource = new DataSource();

                break;
            }
        }

        if (datasource == null) {
            // Handle empty datasources
        }
    }

    public static DataSource getInstance() throws PropertyVetoException {
        /*
         * If the datasource is null the runner is likely to have
         * just been started so use the first shardNode in the list
         */
        if (datasource == null) {
            currentShardNode = shardNodeList.get(0);
            datasource = new DataSource();
        }

        return datasource;
    }

    public Connection getConnection() throws SQLException {
        return this.cpds.getConnection();
    }
}
package com.example.database;
导入java.beans.PropertyVetoException;
导入java.sql.Connection;
导入java.sql.SQLException;
导入java.util.Properties;
导入com.example.base.ShardNode;
导入com.example.manage.ShardManager;
导入com.mchange.v2.c3p0.ComboPooledDataSource;
导入静态com.example.manage.ShardManager.shardNodeList;
//看https://www.javatips.net/blog/c3p0-connection-pooling-example
公共类数据源{
私有静态数据源;
专用组合池数据源CPD;
私有静态int currentsharddid=-1;
私有静态ShardNode currentShardNode;
未指定私有静态布尔值数据库;
私有静态布尔clearConnections=false;
私有静态字符串GetDatabaseUrlAndDB(ShardNodeSelectedShard){
System.out.println(selectedShard.getFullUrl()+ShardManager.getDatabaseName(currentsharddid));
if(未指定数据库){
返回selectedShard.getFullUrl();
}
返回selectedShard.getFullUrl()+ShardManager.getDatabaseName(currentShardId);
}
private DataSource()引发PropertyVetoException{
this.cpds=新的ComboPooledDataSource();
this.cpds.setDriverClass(“com.mysql.cj.jdbc.Driver”);
this.cpds.setJdbcUrl(GetDatabaseUrlAndDB(currentShardNode));
this.cpds.setUser(currentShardNode.getUsername());
this.cpds.setPassword(currentShardNode.getPassword());
//下面的设置是可选的——c3p0可以使用默认值
//设置初始池大小(5);
//设置最小池大小(5);
//cpds.setAcquireIncrement(5);
//cpds.setMaxPoolSize(100);
//cpds.setMaxStatements(100);
/*
*将该值设置为较低,以防止连接在工作人员离开后挂起
*否则会导致在单个节点和服务器上建立过多连接
*开始拒绝新连接。
*/
//设置最大空闲时间(1);
}
/*刷新数据源以使用新id*/
公共静态void switchSource(int shardId,boolean dbNotSpecified)引发PropertyVetoException{
//TODO继续在此处工作。将id传递给数据源并通过凭据
currentShardId=shardId;
dbIsNotSpecified=dbNotSpecified;
for(ShardNode CurrentShard:shardNodeList){
如果((shardId>=CurrentShard.getStartingShard())

&&(shardId在像您这样的长寿命程序中,您必须
.close()
在使用完从
.getConnection()
中获得的任何
连接
对象后才能使用它。如果不这样做,您将得到您在问题中描述的连接泄漏


看起来您的数据源支持池连接。这消除了重复循环
.getConnection()
/
.close()

“我想知道如何最好地关闭这些连接”:使用
连接.close()
或尝试使用资源。很明显,你没有在不可见的代码中的某个地方这样做。谢谢,我会仔细检查。谢谢你在这方面的帮助。我要做的是重新检查代码,仔细检查所有连接等是否关闭,然后从那里开始。看起来这是由于连接未关闭。我所做的一切都是在切换数据库主机之前,使用以下命令关闭连接:datasource.cpds.close();