先简单描述下,因为maxIdle配置的太小(5),导致在性能测试高并发时同一时间闲置的连接超过5,导致连接被关闭,然后就有新的连接被建立。这样关闭的连接就会进入TIME_WAIT,2分钟后才会消失,端口会被占用,但是由于是高并发测试,2分钟有很多这样的连接,超过了可用的端口数。

关键代码

final int maxIdleSave = getMaxIdle();
if (isClosed() || maxIdleSave > -1 && maxIdleSave <= idleObjects.size()) {
    try {
       // 超过了maxIdle就会被立即销毁
        destroy(p);
    } catch (final Exception e) {
        swallowException(e);
    }
    try {
        ensureIdle(1, false);
    } catch (final Exception e) {
        swallowException(e);
    }
}

解决办法:将maxIdle配置与maxActive配置一样的值即可。