druid连接池获取不到连接的⼀种情况
数据源⼀开始配置:
jdbc.initialSize=1
jdbc.minIdle=1
jdbc.maxActive=5
程序运⾏⼀段时间后,执⾏查询抛如下异常:
batis.spring.MyBatisSystemException: nested exception is org.ptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 60000, active 5, maxActive 5
### The error may exist in ...
怀疑是最⼤连接数不够,讲配置改为
jdbc.initialSize=1
jdbc.minIdle=1
jdbc.maxActive=20
<!-- 超过时间限制是否回收 -->
<property name="removeAbandoned" value="true"/>
<!-- 超时时间;单位为秒。180秒=3分钟 -->
<property name="removeAbandonedTimeout" value="180"/>
<!-- 关闭abanded连接时输出错误⽇志 -->
<property name="logAbandoned" value="true"/>
抛如下异常:
2016-12-27 14:35:22.773 [Druid-ConnectionPool-Destroy-1821010113] ERROR com.alibaba.druid.pool.DruidDataSource - abandon connection, owner thread: quartzScheduler_Worker-1, connected time nano: 506518587214834, open stackTrace
at java.StackTrace(Thread.java:1552)
at com.alibaba.druid.ConnectionDirect(DruidDataSource.java:1014)
at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4544)
at com.alibaba.druid.filter.stat.StatFilter.dataSource_getConnection(StatFilter.java:662)
at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4540)
at com.alibaba.druid.Connection(DruidDataSource.java:938)
at com.alibaba.druid.Connection(DruidDataSource.java:930)
at com.alibaba.druid.Connection(DruidDataSource.java:102)
doCopyIn(AppQustionSync.java:168)
ecuteInternal(AppQustionSync.java:99)
at org.springframework.scheduling.ute(QuartzJobBean.java:75)
at JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
红⾊标注处连接未释放,查看代码,
try {
InputStream input = new FileInputStream(dataFile);
conn = Connection();
baseConn = (BaseConnection) MetaData()
.getConnection();
druid连接池配置详解baseConn.setAutoCommit(false);
stmt = ateStatement();
LOG.info("delete data: " + delSql);
CopyManager copyManager = new CopyManager(baseConn);
LOG.info("copy in: " + copyInSql);
baseConnmit();
} catch (SQLException e) {
try {
LOG.warn(JobDataMapHelper.jobName(jobDataMap) + ":"
+ "批量更新任务失败回滚...");
} catch (SQLException ex) {
String errorMessage = String.format(
"JobName:[%s] failed: ",
JobDataMapHelper.jobName(jobDataMap));
throw new SQLException(errorMessage, ex);
}
} finally {
stmt.close();
baseConn.close();
FileUtils.deleteQuietly(dataFile);
}
这⾥baseConn是通过druid datasource获取的⼀个PgSQL 底层连接,上⾯代码执⾏完后,finally中调⽤baseConn.close()关闭了这个连接,(猜测关闭这个底层连接,druid连接池却不知道,还认为⾃⼰拥有这个连接,但实际该连接是不可⽤的,这段代码执⾏多次,就将druid连接池中所有连接都耗光了,于是便抛出Could not get JDBC Connection错误。
将上⾯finally代码块改为
finally {
stmt.close();
conn.close();
FileUtils.deleteQuietly(dataFile);
}
即只调⽤druid 连接的close⽅法(只是释放该连接,⽽不是直接关闭底层连接),问题解决。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。