在AWS上有一个MySQL数据库,我发现在执行show variables like 'max_connections'
操作时,它允许的最大连接数是60
:
所以当使用Apache's javax.sql.DataSource implementation as my connection pool时,我可以将最大值active connections设置为60.
...
connectionPool = new BasicDataSource();
connectionPool.setUrl("...");
connectionPool.setMaxTotal(60);
...
但是,我的代码中有时仍然会出现TooManyConnectionsDatabaseException
个异常.
这让我想知道:这实际上对连接池实现有什么作用?
假设一台服务器只能处理100个活动连接,而我从一个连接池创建了500个连接,那么会发生什么?
-
客户端上的连接池是否创建了400个内部队列并暂停/Hibernate 400个连接线程?
-
或者,它会try 向MySQL数据库发送500个请求,而不考虑设置最大连接数吗?(如果是,限制的意义是什么)
-
或者它是否会为其他400个连接抛出编码异常?
设置连接池的最大活动连接数到底有什么作用?连接池在代码中的行为如何想要创建比您设置的最大值更多的连接?
UPDATE AFTER RIGHT ANSWER个
这是基于@mark-Rotteveel的回答.
通过打印connectionPool.getMaxWaitMillis()
,我看到最大等待时间是-1
毫秒,这意味着Use -1 to make the pool wait indefinitely.
毫秒.
因此,我try 将连接初始化代码更改为:
connectionPool.setMaxTotal(1); // Only have 1 active connection at the same time
connectionPool.setMaxWaitMillis(1); // Only wait 1ms for a free connection
我的代码立刻就得到了
java.sql.SQLException: Cannot get a connection, pool error Timeout waiting for idle object
这是意料之中的,也是有意义的!