在java中,从连接池获取连接花费了太多时间

在java中,从连接池获取连接花费了太多时间,java,jdbc,database-connection,Java,Jdbc,Database Connection,我有一个基于java的web应用程序,其中包含了连接池方法 代码如下: public final class Database { private static final String SQL_EXIST = "show tables;"; public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub } priva

我有一个基于java的web应用程序,其中包含了连接池方法

代码如下:

public final class Database {
    private static final String SQL_EXIST = "show tables;";
    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub
    }

    private static final BasicDataSource dataSource = new BasicDataSource();

    static {
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://link");
        dataSource.setUsername("user");
        dataSource.setPassword("pass");
        dataSource.setMaxTotal(10);
    }

    private Database() {
        //
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}
现在,在我的应用程序中,每当我需要连接时,我都会使用
Database.getConnection()
。问题是,无论何时调用
数据库.getConnection()
,都需要大约900毫秒的时间

我也会在每次DB操作后关闭连接

我使用的代码是:

System.out.println("Time before callingg Func is : "+(System.currentTimeMillis()-main_time));
ABC a=new ABC();    
count = a.d(Database.getConnection(), jObj.getString("a"), jObj.getString("b"),c,jObj.getString("d"),jObj.getString("e"));
System.out.println("Time after callingg Func is : "+(System.currentTimeMillis()-main_time));
我得到的输出是:

Time before callingg Func is : 61
sql Query time is : 266
Time after callingg Func is : 1123
编辑:

我计算了conn未关闭的时间

在进入db函数之前,我还添加了一个时间戳,并在函数的第一行添加了一个时间戳。然后我计算了从第二行到函数末尾的时间,实际上是sql时间

Time before callingg Func is : 68 and time in ms is : 1490001506121
Time in ms when inside function is : 1490001506843
Diff in time is : 722
sql Query time is : 260
Time after callingg Func is : 1050
编辑2

从功能中移除连接部件,即

count = a.d(jObj.getString("a"), jObj.getString("b"),c,jObj.getString("d"),jObj.getString("e"));
然后时间计算是:

Time before callingg Func is : 65 and time in ms is : 1490003211049
Time in ms when inside function is : 1490003211049
Diff in time is : 0
sql Query time is : 1
Time after callingg Func is : 66

为什么不在每次连接后打开一个连接池而不关闭呢。在您的逻辑中验证用户权限,并且连接使用单个应用程序帐户。此链接表示我们应该始终关闭连接。话虽如此,我也尝试不关闭连接。这仍然需要同样的时间。你没有仔细阅读你引用的帖子。在accepted post中,它明确指出对池连接调用
close()
,只会返回到池的连接。我还怀疑您是否正确地测量了时间,因为您声称在不关闭连接的情况下需要相同的时间。在我看来,您测量的是
a.d(…
调用的往返时间,而不仅仅是
getConnection
。我们完全看不到您如何测量“sql查询时间”…那里可能还有很多其他的东西。请检查编辑。我在conn未关闭时添加了时间戳。@Fildor,我正在创建一个变量,名为
long startTime=System.currentTimeMillis();
,最后,就在retune之前,我正在打印
System.out.println(“sql查询时间是:+(System.currentTimeMillis())-开始时间);